ASP.NET MVC中的全局错误处理(控制器外部)

时间:2009-08-31 17:18:12

标签: asp.net-mvc error-handling

假设我将以下代码放在ASP.NET MVC站点的Master页面中:

throw new ApplicationException("TEST");

即使我的控制器上放置了[HandleError]属性,此异常仍会冒泡。我该如何处理这样的错误?我希望能够路由到错误页面,仍然能够记录异常详细信息。

处理这类事情的最佳方法是什么?

编辑:我正在考虑的一个解决方案是添加一个新的控制器:UnhandledErrorController。我可以在Global.asax中放入Application_Error方法然后重定向到此控制器(它决定如何处理异常)?

注意:customErrors web.config元素中的defaultRedirect不会传递异常信息。

5 个答案:

答案 0 :(得分:10)

启用customErrors:

<customErrors mode="On" defaultRedirect="~/Error">
    <error statusCode="401" redirect="~/Error/Unauthorized" />
    <error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>

并重定向到自定义错误控制器:

[HandleError]
public class ErrorController : BaseController
{
    public ErrorController ()
    {
    }

    public ActionResult Index ()
    {
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return View ("Error");
    }

    public ActionResult Unauthorized ()
    {
        Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        return View ("Error401");
    }

    public ActionResult NotFound ()
    {
        string url = GetStaticRoute (Request.QueryString["aspxerrorpath"] ?? Request.Path);
        if (!string.IsNullOrEmpty (url))
        {
            Notify ("Due to a new web site design the page you were looking for no longer exists.", false);
            return new MovedPermanentlyResult (url);
        }

        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View ("Error404");
    }
}

答案 1 :(得分:5)

由于MVC构建于asp.net之上,您应该能够在web.config中定义一个全局错误页面,就像在Web表单中一样。

   <customErrors mode="On" defaultRedirect="~/ErrorHandler" />

答案 2 :(得分:5)

您可以在OnActionExecuted方法中创建一个查找异常的过滤器:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class WatchExceptionAttribute : ActionFilterAttribute {
  public override void OnActionExecuted(ActionExecutedContext filterContext) {
    if (filterContext.Exception != null) {
      // do your thing here.
    }
  }
}

然后你可以将[WatchException]放在Controller或Action方法上,它会让日志异常。如果你有很多控制器,那可能很乏味,所以如果你有一个通用的基本控制器,你可以覆盖OnActionExecuted并执行相同的操作。我更喜欢过滤方法。

答案 3 :(得分:4)

答案 4 :(得分:1)

至于要显示的页面,您需要在web.config中创建customErrors section,并将其设置为您要处理的任何状态代码。

示例:

<customErrors defaultRedirect="GenericError.htm" mode="RemoteOnly">
  <error statusCode="500" redirect="InternalError.htm"/>
</customErrors>

就记录异常而言,我建议使用ELMAH。它与ASP.NET MVC站点很好地集成。

相关问题