title: ASP.NET Core Web Api Middleware Custom Exception
body: <p><strong><em>ASP.NET Core Web Api Middleware Converts Custom Exception into Base Exception</em></strong></p>
  
  <p>I have created a custom exception class and use it throw an exception. The middleware catches it but throws base exception instead of custom exception. I am not able to understand why it does not catch custom exception.</p>
  
  <p><strong><em>Custom Exception</em></strong></p>
  
  <pre class="lang-cs prettyprint-override"><code>public class CustomException : Exception
  {
      public int HttpStatusCode { get; private set; }
  
      public CustomException()
      {
  
      }
  
      public CustomException(int httpStatusCode, string message):base(message)
      {
          HttpStatusCode = httpStatusCode;
      }
  }
  </code></pre>
  
  <p><strong><em>Middleware</em></strong></p>
  
  <pre class="lang-cs prettyprint-override"><code>public class ExceptionMiddleware
  {
      public readonly RequestDelegate _next;
      public ExceptionMiddleware(RequestDelegate next)
      {
          _next = next;
      }
  
      public async Task InvokeAsync(HttpContext httpContext)
      {
          try
          {
              await _next(httpContext);
          }
          catch(CustomException ex)
          {
              await HandleExceptionAsync(httpContext, ex);
          }
          catch(Exception ex)
          {
              await HandleExceptionAsync(httpContext, ex);
          }
      }
  
      private static Task HandleExceptionAsync(HttpContext context, Exception ex)
      {
          int statusCode = (int)HttpStatusCode.InternalServerError;
          if (ex is CustomException)
          {
              CustomException se = ex as CustomException;
              statusCode = se.HttpStatusCode;
          }
          context.Response.ContentType = "application/json";
          context.Response.StatusCode = statusCode;
  
          return context.Response.WriteAsync(JsonConvert.SerializeObject(new InternalServerErrorResponse(ex.Message)));
      }
  }
  </code></pre>
  
  <p><strong><em>Exception thrown</em></strong></p>
  
  <pre class="lang-cs prettyprint-override"><code>throw new CustomException(StatusCodes.Status422UnprocessableEntity, "User is already registered!");
  </code></pre>
  
  <p>When exception is thrown, middleware does not catch custom exception but base Exception. It always goes to the below code block</p>
  
  <pre class="lang-cs prettyprint-override"><code>catch(Exception ex)
  {
       await HandleExceptionAsync(httpContext, ex);
  }
  </code></pre>
  
  <p>Please advise.</p>