How-To setup global exception handler in .NET Core?1 min read

Today I’ll try to be precise and straight to the point as possible.
If you want to simplify your code by removing unnecessary try {} catch {} blocks of your code inside API Controllers, then you probably want to use some kind of global hook in which you are going to handle global exceptions.

The way we utilize global exception handler in .NET Core API is like this:

Startup.cs -> Configure method:

app.UseExceptionHandler(builder => { builder.Run(async context =>
{
     context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
​
     var exceptionHandler = context.Features.Get<IExceptionHandlerFeature>();
​
     if (exceptionHandler != null)
     {
          await context.Response.WriteAsync(exceptionHandler.Error.Message);
     }
​
}); });

But this way we did not set up our CORS headers we only set our error message.

Add IHttpResponse extension

So to fix our CORS headers we need to add an extension which is going to do just that, set our CORS headers. We will also add the possibility to set our custom error message as well.

The way we do it, is like this:

public static class Extensions
{
    public static void AddApplicationExceptionHandlerCorsHeaderWithMessage(this HttpResponse httpResponse, string customErrorMessage)
    {
        httpResponse.Headers.Add("Application-Error", customErrorMessage);
        httpResponse.Headers.Add("Access-Control-Expose-Headers", "Application-Error");
        httpResponse.Headers.Add("Access-Control-Allow-Origin", "*");
    }
}

And now we have proper global exception handler set up with CORS and header error message.

FINAL RESULT:

app.UseExceptionHandler(builder => { builder.Run(async context =>
{
     context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
​
     var exceptionHandler = context.Features.Get<IExceptionHandlerFeature>();
​
     if (exceptionHandler != null)
     {
          var errorMessage = exceptionHandler.Error.Message;
 
 context.Response.AddApplicationExceptionHandlerCorsHeaderWithMessage(errorMessage);
     await context.Response.WriteAsync(errorMessage);
    }
​}); });

Leave a Reply

Your email address will not be published. Required fields are marked *