bre*_*ree 23 c# exception-handling asp.net-mvc-4
是否有更好的方法来捕获异常?我好像在复制很多代码.基本上在每个控制器中我都有一个catch语句来执行此操作:
try
{
Do something that might throw exceptions.
}
catch (exception ex)
{
Open database connection
Save exception details.
If connection cannot be made to the database save exception in a text file.
}
Run Code Online (Sandbox Code Playgroud)
我在每个控制器中有4个控制器和大约5-6个动作方法,这是很多代码重复.如何减少上面try catch语句中的行数?
Har*_*der 40
您可以在此处使用Extension方法.
在新类中创建扩展方法.
public static class ExtensionMethods
{
public static void Log(this Exception obj)
{
// log your Exception here.
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它像:
try
{
}
catch (Exception obj)
{
obj.Log();
}
Run Code Online (Sandbox Code Playgroud)
Job*_*mno 13
您不需要在每个方法上放置try/catch块.那是乏味而痛苦的!相反,您可以使用Global.asax 的Application_Error事件来记录异常.下面的代码是示例实现,可用于捕获Web应用程序中发生的异常.
protected void Application_Error(object sender, EventArgs e)
{
var error = Server.GetLastError();
if (!string.IsNullOrWhiteSpace(error.Message))
{
//do whatever you want if exception occurs
Context.ClearError();
}
}
Run Code Online (Sandbox Code Playgroud)
我还要强调,"处理异常"特别是尝试在大多数方法上放置try/catch块是"IIS/ASP.NET应用程序的前三大静默性能杀手"之一,如本博客中所述:http:// mvolo的.com/FIX-所述-3-高CPU-性能问题换IIS-ASPNET的应用程式/
Wou*_*ort 11
你想要做的事情被称为跨领域的关注点.您正在尝试记录代码中任何位置发生的任何错误.
在ASP.NET MVC中,可以通过使用过滤器来实现横切关注.过滤器是可以全局应用于控制器或方法的属性.它们在执行操作方法之前或之后运行.
您有几种类型的过滤器:
在您的情况下,您正在寻找异常过滤器.这些过滤器仅在操作方法中发生异常时运行.您可以全局应用过滤器,以便它可以自动运行任何控制器中的所有异常.您也可以专门在某些控制器或方法上使用它.
在MSDN文档中,您可以找到如何实现自己的过滤器.
| 归档时间: |
|
| 查看次数: |
2057 次 |
| 最近记录: |