title: Catch all exception in ASP.NET MVC + Web Api
body: <p>I know there are plenty of threads about this topic but none provides an entire and full working solution.</p>
  
  <h2>Scenario</h2>
  
  <p>I have an application which is providing both, MVC 5 and Web Api 2.2 controllers.
  I have the need of catching all exceptions (including 404, 401) and return always a custom JSON error structure.</p>
  
  <h2>Partial Solution</h2>
  
  <p>So far I have implemented, a custom <code>ExceptionFilterAttribute</code> as following:</p>
  
  <pre><code>public class ExceptionFilter : ExceptionFilterAttribute
  {
      public override void OnException(HttpActionExecutedContext context)
      {
          context.Response = context.Request.CreateResponse(
              HttpStatusCode.InternalServerError,
              new
              {
                  Title = "An Error occured while processing the request",
                  Message = context.Exception.ToString(),
                  Type = "Error",
                  Code = context.Exception.HResult
              });
          context.Response.ReasonPhrase = "An Error occurred while processing the request";
      }
  }
  </code></pre>
  
  <p>Then I also extended and replaced the available ExceptionHandler service as following:</p>
  
  <pre><code>public class GenericExceptionHandler : ExceptionHandler
  {
      public override void Handle(ExceptionHandlerContext context)
      {
          context.Result = HttpResponseFactory.BadResponse(
              context.Request,
              "An unhandled error occurred",
              context.Exception.Message,
              10000);
      }   
  }
  </code></pre>
  
  <p>And I swap both during my initialization:</p>
  
  <pre><code>public static void Register(HttpConfiguration config)
  {
      // authentication
      config.Filters.Add(new AuthorizeAttribute());
      // error handler
      config.Filters.Add(new ExceptionFilter());
      // error service
      config.Services.Replace(typeof(IExceptionHandler), new GenericExceptionHandler());
  }
  </code></pre>
  
  <p>Unfortunately when I generate:</p>
  
  <ol>
  <li>401 - Not Authorized</li>
  <li>404 - Not Found</li>
  <li>certain 500 - Internal Server Error</li>
  </ol>
  
  <p>I cannot catch the exception. Is there any way to achieve it?</p>