【问题标题】:Best practices for asp.net mvc error handling [closed]asp.net mvc 错误处理的最佳实践 [关闭]
【发布时间】:2011-05-30 06:12:26
【问题描述】:

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

  • 404 错误处理程序
  • 控制器范围异常错误处理程序
  • 全局范围异常错误处理程序

【问题讨论】:

  • frig 这真是个问题。如您所料,MVC 绝对不支持它。

标签: asp.net-mvc error-handling


【解决方案1】:

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

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

     }
}

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

[RedirectOnError]
public class TestController : Controller
{
     //.. Actions etc...
}

如果错误与路由有关,则无济于事 - 即它首先找不到控制器。为此,请尝试 Global.asax 中的应用程序错误处理程序,即

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

我不知道这是否是“最佳实践”。行得通。

【讨论】:

    【解决方案2】:

    Here 是您问题中“404”部分的最详细答案。尽管主题是 404,但它会让您了解如何将其应用于其他错误类型。

    虽然,我无法将其明确说明为“最佳实践”,因为您需要使用该方法的层超类型控制器。我最好在Global.asax 中抓住那些HttpExceptions。但在大多数情况下,它是一个很好的指南。

    至于整个 MVC 应用程序中的任意异常 - 不要忘记 HandleErrorAttribute

    【讨论】:

      【解决方案3】:

      不确定最佳实践,并且取决于您想对错误做什么,一个简单的解决方案不是使用 web.config 文件中的 customErrors 设置吗?

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

      另外,看看这个SO post

      【讨论】:

        猜你喜欢
        • 2016-06-06
        • 2014-11-28
        • 2020-12-24
        • 2013-05-04
        • 2010-11-16
        • 1970-01-01
        • 1970-01-01
        • 2011-07-28
        • 2018-09-12
        相关资源
        最近更新 更多