title: ASP.NET Core Web API exception handling
body: <p>I am using ASP.NET Core for my new REST API project after using regular ASP.NET Web API for many years. I don't see any good way to handle exceptions in ASP.NET Core Web API. I tried to implement an exception handling filter/attribute:</p>
  <pre><code>public class ErrorHandlingFilter : ExceptionFilterAttribute
  {
      public override void OnException(ExceptionContext context)
      {
          HandleExceptionAsync(context);
          context.ExceptionHandled = true;
      }
  
      private static void HandleExceptionAsync(ExceptionContext context)
      {
          var exception = context.Exception;
  
          if (exception is MyNotFoundException)
              SetExceptionResult(context, exception, HttpStatusCode.NotFound);
          else if (exception is MyUnauthorizedException)
              SetExceptionResult(context, exception, HttpStatusCode.Unauthorized);
          else if (exception is MyException)
              SetExceptionResult(context, exception, HttpStatusCode.BadRequest);
          else
              SetExceptionResult(context, exception, HttpStatusCode.InternalServerError);
      }
  
      private static void SetExceptionResult(
          ExceptionContext context, 
          Exception exception, 
          HttpStatusCode code)
      {
          context.Result = new JsonResult(new ApiResponse(exception))
          {
              StatusCode = (int)code
          };
      }
  }
  </code></pre>
  <p>And here is my Startup filter registration:</p>
  <pre><code>services.AddMvc(options =&gt;
  {
      options.Filters.Add(new AuthorizationFilter());
      options.Filters.Add(new ErrorHandlingFilter());
  });
  </code></pre>
  <p>The issue I was having is that when an exception occurs in my <code>AuthorizationFilter</code> it's not being handled by <code>ErrorHandlingFilter</code>. I was expecting it to be caught there just like it worked with the old ASP.NET Web API.</p>
  <p>So how can I catch all application exceptions as well as any exceptions from Action Filters?</p>