How do I handle uncaught exceptions in an ASP.NET MVC 3 application?

后端 未结 5 812
情书的邮戳
情书的邮戳 2020-12-29 06:27

I want to handle uncaught exceptions in my ASP.NET MVC 3 application, so that I may communicate the error to the user via the application\'s error view. How do I intercept u

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 06:57

    you can use HandleErrorAttribute filters,

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

    basically you can have this on top of a base controller and define the UnhandledError.cshtml in the Shared views folder.

    And if you want to log the unhandled errors before you show the error message then you can extend the HandleErrorAttribute class and put the logic to do the logging inside the OnException method.

    public class MyErrorHandlerAttribute : HandleErrorAttribute
        {
    
    
            public override void OnException(ExceptionContext exceptionContext)
            {
                Logger.Error(exceptionContext.Exception.Message,exceptionContext.Exception);
                base.OnException(exceptionContext);
            }
        }
    

提交回复
热议问题