Application_Error event in global.asax not firing

1.3k Views Asked by At

I'm having an issue where the Application_Error event does not seem to fire when I explicitly throw a page-level exception.

My Global.asax.cs file is as follow:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            CustomExceptionClass.BootstrapEnterpriseLibrary();  
    }

    // Event handler that passes all exceptions not in a catch statement 
    // to the handler

    protected void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();
        CustomExceptionClass.HandleException(ex);
        Server.ClearError();
    }
}

public class ExceptionPublisherExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext exceptionContext)
    {
        var exception = exceptionContext.Exception;
        CustomExceptionClass.HandleException(exception);
    }
}

public class ErrorHandler : IErrorHandler
{
    public void ProvideFault(Exception error, MessageVersion version, 
        ref Message fault)
    {
    }

    public bool HandleError(Exception error)
    {
        CustomExceptionClass.HandleException(error);
        return true;
    }
}

My web.config file has <customErrors mode="Off">.

My filterconfig looks like the following:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new ExceptionPublisherExceptionFilter());
    //filters.Add(new HandleErrorAttribute());
}

I have tried the following fixes:

  • Change customErrors to on or off
  • Implement a new filter and add it to filterconfig

Whenever I throw an exception in VS, I try to step into it, but it just keeps on running. Does anyone know why Application_Error isn't being fired?

Edit: It looks like the scope affects whether Application_Error gets called. So the question is really, why Application_Error isn't being called at the page-level.

1

There are 1 best solutions below

0
user1007074 On

In case you were testing this with an HttpResponseException it turns out that those are ignored by ApiExceptionHandler and derived classes by design and will never result in Application_Error firing. Switch to another Exception type to address the issue.