Skip to main content

GlobalExceptionHandler

Namespace: RA.Utilities.Api.ExceptionHandlers

The GlobalExceptionHandler is a crucial component in your API's architecture. It acts as a centralized, last-resort safety net for your entire application. Its primary purpose is to catch any unhandled exceptions that occur during the processing of an HTTP request, ensuring that your API never crashes and always returns a predictable, structured error response to the client.

It performs three key actions:

  • 1. Logs the Error: It uses the standard ILogger to log the full exception details. Client errors (4xx) — such as BadRequestException, NotFoundException, ConflictException, PaymentRequiredException, or TooManyRequestsException — are logged as warnings, while server errors (5xx) and unrecognized exceptions are logged as errors. This keeps expected client mistakes out of the error logs while surfacing genuine server failures, which is critical for developers to diagnose and fix bugs.
  • 2. Maps the Exception: It calls ErrorResultResponse.Result(exception). This is a smart mapper that inspects the type of exception. If it's a known, semantic exception from your RA.Utilities.Core.Exceptions library (like NotFoundException or BadRequestException), it creates a specific, structured JSON response with the appropriate HTTP status code (e.g., 404 or 400). For example, a PaymentRequiredException becomes an HTTP 402 response with a PaymentRequiredResponse body. For any other unexpected exception, it generates a generic "Internal Server Error" (500) response to avoid leaking sensitive implementation details.
  • 3. Writes the Response: It takes the generated error response and writes it to the HTTP response stream, completing the request gracefully from the client's perspective.

By implementing the IExceptionHandler interface (a feature introduced in .NET 8), this class integrates cleanly into the ASP.NET Core request pipeline, replacing older, more complex custom middleware solutions.

🚀 Usage Guide​

The handler is registered with the dependency injection container and added to the request pipeline via the ServiceCollectionExtensions and ApplicationBuilderExtensions classes:

using RA.Utilities.Api.Extensions;

WebApplicationBuilder builder =
WebApplication.CreateBuilder(args);

// Registers the GlobalExceptionHandler with DI
// (equivalent to builder.Services.AddExceptionHandler<GlobalExceptionHandler>())
builder.Services
.AddRaExceptionHandling();

WebApplication app = builder.Build();

// Adds the exception handler middleware to the pipeline
// (equivalent to app.UseExceptionHandler())
app.UseRaExceptionHandling();

app.Run();