When will an MVC ExceptionFilter be executed vs the application-level error handler?

Viewed 1377

I have a custom exception FilterAttribute such as the following:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class ExceptionLoggingFilterAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException(nameof(filterContext));
        }

        if (filterContext.ExceptionHandled)
        {
            return;
        }

        // some exception logging code (not shown)

        filterContext.ExceptionHandled = true;
}

I have this registered globally in my FilterConfig.cs

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

I also have an Application_Error method declared in my global.asax.cs

protected void Application_Error(object sender, EventArgs e)
    {
        var exception = Server.GetLastError();

        // some exception logging code (not shown)
    }
  1. When will the exception filter code be hit and when will it go straight to the global error handler in the Application_Error method? (I understand the ExceptionHandled concept and realise that by marking that as handled in my filter, it won't then cascade up to the global error handler).

An exception that I thought would hit the filter - an HttpException for 404, does not hit the filter but does get caught in the application error handler.

  1. I have seen some code samples where people use the HttpContext.Current in the global.asax.cs to do a Server.TransferRequest to a specific error view. Is this best practice? Would it be better to use the CustomErrors section in the system.web section of the web.config?
1 Answers
Related