如何在ASP.NET MVC 3应用程序中处理未捕获的异常?

akn*_*ds1 19 asp.net-mvc exception-handling asp.net-mvc-3

我想在我的ASP.NET MVC 3应用程序中处理未捕获的异常,以便我可以通过应用程序的错误视图将错误传达给用户.如何拦截未捕获的异常?我希望能够在全球范围内做到这一点,而不是每个控制器(尽管我不介意知道如何做到这一点).

fea*_*net 19

您可以在中设置全局错误过滤器 Global.asax

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}
Run Code Online (Sandbox Code Playgroud)

上面设置了一个默认的错误处理程序,它将所有异常定向到标准错误V​​iew.错误视图键入到System.Web.Mvc.HandleErrorInfo公开异常详细信息的模型对象.

您还需要在web.config中打开自定义错误,才能在本地计算机上看到此错误.

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

您还可以为特定错误类型定义多个过滤器:

filters.Add(new HandleErrorAttribute
{
    ExceptionType = typeof(SqlException),
    View = "DatabaseError",
    Order = 1
});

/* ...other error type handlers here */

filters.Add(new HandleErrorAttribute()); // default handler
Run Code Online (Sandbox Code Playgroud)

请注意,它HandleErrorAttribute只会处理MVC管道内发生的错误(即500个错误).


Ill*_*ati 10

你可以使用HandleErrorAttribute过滤器,

[ErrorHandler(ExceptionType = typeof(Exception), View = "UnhandledError", Order = 1)]
 public abstract class BaseController : Controller

        {
    }
Run Code Online (Sandbox Code Playgroud)

基本上你可以在基本控制器上安装它,并在共享视图文件夹中定义UnhandledError.cshtml.

如果要在显示错误消息之前记录未处理的错误,则可以扩展HandleErrorAttribute类并将逻辑放在OnException方法内部进行日志记录.

public class MyErrorHandlerAttribute : HandleErrorAttribute
    {


        public override void OnException(ExceptionContext exceptionContext)
        {
            Logger.Error(exceptionContext.Exception.Message,exceptionContext.Exception);
            base.OnException(exceptionContext);
        }
    }
Run Code Online (Sandbox Code Playgroud)