title: ASP.Net Core exception handling middleware
body: <p>I am trying to use middleware for exception handling in my ASP.Net Core 3.0 Web API project:</p>
  
  <pre><code>public class ErrorHandlingMiddleware
  {
      private readonly RequestDelegate next;
  
      public ErrorHandlingMiddleware(RequestDelegate next)
      {
          this.next = next;
      }
  
      public async Task Invoke(HttpContext context)
      {
          try
          {
              await next(context);
          }
          catch (Exception ex)
          {
              await HandleException(context, ex);
          }
      }
  
      private static Task HandleException(HttpContext context, Exception ex)
      {
          HttpStatusCode code = HttpStatusCode.InternalServerError; // 500 if unexpected
  
          // Specify different custom exceptions here
          if (ex is CustomException) code = HttpStatusCode.BadRequest;
  
          string result = JsonConvert.SerializeObject(new { error = ex.Message });
  
          context.Response.ContentType = "application/json";
          context.Response.StatusCode = (int)code;
  
          return context.Response.WriteAsync(result);
      }
  }
  </code></pre>
  
  <p><em>startup.cs</em></p>
  
  <pre><code>public class Startup
  {
      public Startup(IConfiguration configuration)
      {
          Configuration = configuration;
      }
  
      public IConfiguration Configuration { get; }
  
      // This method gets called by the runtime. Use this method to add services to the container.
      public void ConfigureServices(IServiceCollection services)
      {
          // Add controllers with a route prefix
          services.AddControllers(x =&gt; { x.UseGeneralRoutePrefix($"api/v{Configuration["APIVersion"]}"); });
          services.AddSwaggerGen(c =&gt;
          {
              c.SwaggerDoc("v0.1", new OpenApiInfo { Title = "My API", Version = "v0.1" });
          });
      }
  
      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
          }
  
          app.UseHttpsRedirection();
  
          app.UseSwagger();
          app.UseSwaggerUI(c =&gt;
          {
              c.SwaggerEndpoint("/swagger/v0.1/swagger.json", "My API V1");
          });
  
          app.UseMiddleware(typeof(ErrorHandlingMiddleware));
  
          app.UseRouting();
  
          app.UseAuthorization();
  
          app.UseEndpoints(endpoints =&gt;
          {
              endpoints.MapControllers();
          });
      }
  }
  </code></pre>
  
  <p>Controller</p>
  
  <pre><code>[HttpPost]
  public ActionResult Method()
  {
      if (condition)
          throw new CustomException();
      else
          return Ok();
  }
  </code></pre>
  
  <p>but the exception thrown in the controller doesn't get handled by the middleware. What would be the correct way to use the middleware?</p>