简体   繁体   中英

Catch Unhandled exception in mvc4

How can i catch unhandeld exception in mvc4, [without using ELMAH]. I tried Invoking Application_Error , it works but logs all error including script not found and path of image not found which is not needed.

Example of error which can be excluded

The controller for path '/Image/*.png' was not found or does not implement IController

The controller for path '/~/Scripts/*.js' was not found or does not implement IController

Code

void Application_Error(object sender, EventArgs e) 
{
   Exception exc = Server.GetLastError();
   //logging Exception (exc)
 }

Create a custom error handler and catch what you want (and log it) and ignore what you don't want.

CustomHandleErrorAttribute

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (!(filterContext.Exception is InvalidOperationException))
        {
            // log
        }
    }
}

FilterConfig

You will need to globally register the error handler.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new CustomHandleErrorAttribute());
    }
}

these Errors are unhandled exception.i think you can get this error type and ignore it for logging

  protected void Application_Error()
    {

        var ex = Server.GetLastError();

        if(check exceptiontype)
        {}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM