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

use*_*789 7 error-handling asp.net-mvc

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

throw new ApplicationException("TEST");
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Tod*_*ith 10

启用customErrors:

<customErrors mode="On" defaultRedirect="~/Error">
    <error statusCode="401" redirect="~/Error/Unauthorized" />
    <error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>
Run Code Online (Sandbox Code Playgroud)

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

[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");
    }
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*plo 5

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

   <customErrors mode="On" defaultRedirect="~/ErrorHandler" />
Run Code Online (Sandbox Code Playgroud)

  • 那我该如何检索异常细节呢? (7认同)

swi*_*ams 5

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

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

然后你可以放置[WatchException]一个Controller或Action方法,它会让日志异常.如果你有很多控制器,这可能是乏味的,所以如果你有一个共同的基本控制器,你可以覆盖OnActionExecuted那里并做同样的事情.我更喜欢过滤方法.