asp.net mvc错误处理的最佳实践

non*_*.cs 14 error-handling asp.net-mvc

我正在寻找一种标准方法来处理asp.net mvc 2.0或3.0中的错误

  • 404错误处理程序
  • Controller范围异常错误处理程序
  • 全局范围异常错误处理程序

Cra*_*ket 8

对于控制器范围错误,请尝试使用自定义Exception属性,即

public class RedirectOnErrorAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {

        // Don't interfere if the exception is already handled
        if(filterContext.ExceptionHandled)
        return;

        //.. log exception and do appropriate redirects here

     }
}
Run Code Online (Sandbox Code Playgroud)

然后用属性装饰控制器,错误处理应该是你的

[RedirectOnError]
public class TestController : Controller
{
     //.. Actions etc...
}
Run Code Online (Sandbox Code Playgroud)

如果错误与路由有关,则无效 - 即它首先找不到控制器.为此尝试Global.asax中的Application Error处理程序ie

 protected void Application_Error(object sender, EventArgs e)
 {
      //.. perhaps direct to a custom error page is here
 }
Run Code Online (Sandbox Code Playgroud)

我不知道这是否是"最佳做法".有用吗


mac*_*cou 1

不确定最佳实践,并且根据您想要对错误执行的操作,一个简单的解决方案不是使用 web.config 文件中的 customErrors 设置吗?

为了捕获未处理的错误,我有时会使用 Global.asax 文件中的 Application_Error 方法。

另外,看看这个帖子