Skip to content

Global Exception Filter in an ASP.NET Core Application

Problem definition: We need to handle exceptions thrown by an ASP.NET Core application. For example, if a developer forgets to write exception-handling code for a feature, users see an unhandled exception in production, which is bad practice. So here we write a global exception handler for the whole application.

In ASP.NET Core we can handle exceptions in many ways. In this article, I explain how to do it with a global exception handler that uses the IExceptionHandler interface. Below is the step-by-step process, explained in detail, so that you can create a Web API project and learn exception handling in ASP.NET Core.

Create a Web API project in Microsoft Visual Studio
Select the ASP.NET Core Web API project type and click OK. Your Solution Explorer will look like the image below.

Your Solution Explorer looks like the image below.

Solution Explorer of the ASP.NET Core Web API project

Create a folder in Solution Explorer, add a class named GlobalExceptionHandler, implement the IExceptionHandler interface and provide the TryHandleAsync method, as you can see in the image below.

GlobalExceptionHandler class implementing IExceptionHandler.TryHandleAsync
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger,
      IHostEnvironment env) : IExceptionHandler
  {
      public async ValueTask<bool> TryHandleAsync(HttpContext httpContext,Exception exception,
      CancellationToken cancellationToken)
      {
          logger.LogError(exception, "An unhandled exception occurred: {Message}", exception.Message);
          var isDev = env.IsDevelopment();
          // Standardized Problem Details response
          var problemDetails = new ProblemDetails
          {
              Status = (int)HttpStatusCode.InternalServerError,
              Title = "Server Error",
              Detail = "An unexpected error occurred on our end. Please try again later.",
              Instance = httpContext.Request.Path
          };
          // Only show technical details (Stack Trace) in Development
          if (isDev)
          {
              problemDetails.Extensions["stackTrace"] = exception.StackTrace;
          }
          httpContext.Response.StatusCode = problemDetails.Status.Value;

          await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);

          // Return true to signal that the exception has been handled
          return true;
      }
  } 

In the code above, the GlobalExceptionHandler class takes ILogger and IHostEnvironment in its constructor and implements the TryHandleAsync method of the IExceptionHandler interface, which accepts three parameters: the HttpContext, the Exception and a CancellationToken.

Inside the method, we create a ProblemDetails object and set the status code and a meaningful message for end users. In the response, we write one general message for every unhandled exception in the application.

After creating the global exception handler, register it in the Program.cs file, as shown in the image below.

Registering the global exception handler in Program.cs

The code for the Program.cs file:

  builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
app.UseExceptionHandler();

Run the application. When you call the URL for the error-prone code, you get the response below, which confirms that our global exception handling works in the ASP.NET Core application. See the image below for the URL.

API error response returned by the global exception handler