Skip to content

C# Interview Guide: Global Exception Handling with IExceptionHandler (.NET 8)

Q10 — Global Exception Handling with IExceptionHandler (.NET 8) Level: Senior | Topic: Web API The Problem Without centralised exception handling, every controller action needs its own try/catch, error responses are inco...

Ekanatha Reddy Urivakili15 min2,316 words

Q10 — Global Exception Handling with IExceptionHandler (.NET 8)

Level: Senior | Topic: Web API

Centralized exception handling is a critical capability in modern Web APIs to ensure consistent error responses, improve observability, and avoid leaking sensitive server details. In this guide, we explore the new IExceptionHandler interface introduced in .NET 8, how to implement it effectively, and best practices to adopt.

The Problem

In typical ASP.NET Core Web API projects prior to .NET 8, exception handling often happens ad hoc, sprinkled with try/catch blocks inside controller actions or middleware. This approach quickly devolves into:

  • Repetitive code: Every controller or action duplicates error handling logic.
  • Inconsistent responses: Different errors lead to inconsistent HTTP status codes and response payload schemas.
  • Security risk: Raw exception messages or stack traces can leak internals to clients.
  • Poor observability: Lost or inconsistent correlation IDs hamper tracing and diagnostics across distributed systems.

While custom middleware or filters were used to solve parts of this problem, the new IExceptionHandler interface in .NET 8 formalizes a clean, extensible pattern.

Overview of IExceptionHandler

The .NET 8 release introduced IExceptionHandler as the canonical, framework-supported way to globally handle exceptions in ASP.NET Core Web APIs.

The interface has a single method:

ValueTask<bool> TryHandleAsync(
    HttpContext context,
    Exception exception,
    CancellationToken cancellationToken);

If your implementation returns true, it means the exception was handled and the pipeline stops propagating the error further.

Multiple handlers can be registered and chained, and the first one to handle the exception short-circuits processing.

This enables clean separation of concerns — e.g., domain exceptions handled by one handler, infrastructural exceptions handled by another, etc.

Together with middleware and ProblemDetails (RFC 7807) support, this interface enables consistent, standards-based error responses with out-of-the-box extensibility.

High-Level Architecture (HLD)

flowchart TD
    A[Incoming HTTP Request] --> B[Middleware]
    B --> C{Exception occurs?}
    C -- No --> D[Controller executes normally]
    C -- Yes --> E[Exception captured by UseExceptionHandler()]
    E --> F[Registered IExceptionHandler instances]
    F -->|TryHandleAsync| G{Handler returns true?}
    G -- Yes --> H[Response written as ProblemDetails JSON]
    G -- No --> I[Next IExceptionHandler tries or fallback to default]
    H --> J[Response sent to client]
    I --> J

High-level flow of exception handling using IExceptionHandler and UseExceptionHandler middleware

Sequence Diagram: Exception Handling Pipeline

sequenceDiagram
    participant Client
    participant Server
    participant Middleware as Exception Middleware
    participant Handler1 as DomainExceptionHandler
    participant Handler2 as FallbackExceptionHandler

    Client->>Server: HTTP Request
    Server->>Middleware: Process Request
    Middleware->>Server: Exception thrown
    Middleware->>Handler1: TryHandleAsync(exception)
    Handler1-->>Middleware: false (cannot handle)
    Middleware->>Handler2: TryHandleAsync(exception)
    Handler2-->>Middleware: true (handled)
    Middleware->>Client: HTTP Response with ProblemDetails JSON

Sequence diagram showing exception capture and handling delegation


Implementing Global Exception Handling in .NET 8

Setting Up the Exception Handler in Program.cs

First, register your global exception handler implementation and configure middleware:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddExceptionHandler<GlobalExceptionHandler>(); // Register handler
builder.Services.AddProblemDetails();                           // Add RFC7807 middleware support

var app = builder.Build();

app.UseExceptionHandler();  // Insert middleware before routing/endpoint middleware

app.MapControllers();

app.Run();

Creating Your GlobalExceptionHandler Implementation

using System.Threading;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

public sealed class GlobalExceptionHandler : IExceptionHandler
{
    private readonly ILogger<GlobalExceptionHandler> _logger;

    public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
        => _logger = logger;

    public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
    {
        var correlationId = context.Items["CorrelationId"]?.ToString() ?? Guid.NewGuid().ToString();
        _logger.LogError(exception, "Unhandled exception. CorrelationId: {CorrelationId}", correlationId);

        var (status, title, detail) = exception switch
        {
            NotFoundException e         => (404, "Resource not found", e.Message),
            ValidationException e       => (422, "Validation failed", e.Message),
            UnauthorizedAccessException => (403, "Forbidden", "Access denied"),
            ConflictException e         => (409, "Conflict", e.Message),
            OperationCanceledException  => (499, "Request cancelled", "Client closed request"),
            _                           => (500, "Internal server error", "An unexpected error occurred"),
        };

        context.Response.StatusCode = status;
        context.Response.ContentType = "application/problem+json";

        var problemDetails = new ProblemDetails
        {
            Status = status,
            Title = title,
            Detail = detail,
            Instance = $"{context.Request.Method} {context.Request.Path}",
            Extensions = { ["correlationId"] = correlationId }
        };

        await context.Response.WriteAsJsonAsync(problemDetails, ct);

        return true; // Exception has been handled
    }
}

Domain Exception Classes

To enforce semantic exception handling, define a domain-specific hierarchy:

public abstract class DomainException : Exception
{
    protected DomainException(string message) : base(message) { }
}

public sealed class NotFoundException : DomainException
{
    public NotFoundException(string type, object id)
        : base($"{type} with id '{id}' was not found") { }
}

public sealed class ValidationException : DomainException
{
    public ValidationException(string message) : base(message) { }
}

public sealed class ConflictException : DomainException
{
    public ConflictException(string message) : base(message) { }
}

Comparing Exception Handling Strategies in ASP.NET Core

StrategyProsConsUse Cases
Try/catch in Controller ActionsComplete control on per-action basisCode duplication, inconsistent responses, error-proneSmall/simple apps
Exception Filter (IExceptionFilter)Centralizes logic per controller or globallyLimited to MVC pipeline, cannot catch exceptions in middlewareMVC apps, synchronous handlers
Custom MiddlewareGlobal scope, can handle async exceptionsMore boilerplate, less declarativeOlder projects before .NET 8
IExceptionHandler (.NET 8)Clean, composable, chainable handlers, built-in framework supportRequires .NET 8+, learning new interfaceModern ASP.NET Core Web APIs

Real-World Code Example: Chaining Multiple Exception Handlers

Suppose you want a separate handler for domain exceptions and a fallback for others.

public sealed class DomainExceptionHandler : IExceptionHandler
{
    private readonly ILogger<DomainExceptionHandler> _logger;

    public DomainExceptionHandler(ILogger<DomainExceptionHandler> logger)
        => _logger = logger;

    public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
    {
        if (exception is DomainException domainEx)
        {
            _logger.LogWarning(domainEx, "Domain exception caught");

            context.Response.StatusCode = exception switch
            {
                NotFoundException => 404,
                ValidationException => 422,
                ConflictException => 409,
                _ => 400
            };
            context.Response.ContentType = "application/problem+json";

            var problem = new ProblemDetails
            {
                Status = context.Response.StatusCode,
                Title = "Domain error",
                Detail = domainEx.Message,
                Instance = $"{context.Request.Method} {context.Request.Path}"
            };

            await context.Response.WriteAsJsonAsync(problem, ct);
            return true;
        }

        return false; // Not handled, let next handler try
    }
}

public sealed class FallbackExceptionHandler : IExceptionHandler
{
    private readonly ILogger<FallbackExceptionHandler> _logger;

    public FallbackExceptionHandler(ILogger<FallbackExceptionHandler> logger)
        => _logger = logger;

    public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
    {
        _logger.LogError(exception, "Unhandled exception");

        context.Response.StatusCode = 500;
        context.Response.ContentType = "application/problem+json";

        var problem = new ProblemDetails
        {
            Status = 500,
            Title = "Internal server error",
            Detail = "An unexpected error occurred",
            Instance = $"{context.Request.Method} {context.Request.Path}"
        };

        await context.Response.WriteAsJsonAsync(problem, ct);

        return true;
    }
}

Registering Multiple Handlers in Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddExceptionHandler<DomainExceptionHandler>();
builder.Services.AddExceptionHandler<FallbackExceptionHandler>();
builder.Services.AddProblemDetails();

var app = builder.Build();
app.UseExceptionHandler();

app.MapControllers();
app.Run();

Observability: Logging, Metrics, and Tracing

Reliable global error handling is only useful with robust observability.

What to Log

  • Exception messages and stack traces (only in logs, never expose in responses)
  • Correlation ID for distributed tracing
  • Request path, method
  • User context if available
  • Custom error codes or domain exception types

Structured Log Example (JSON):

{
  "timestamp": "2024-06-20T12:34:56Z",
  "level": "Error",
  "message": "Unhandled exception",
  "correlationId": "123e4567-e89b-12d3-a456-426614174000",
  "exception": {
    "type": "NotFoundException",
    "message": "User with id '42' was not found",
    "stackTrace": "at MyApp.Controllers.UserController.GetUser(...)"
  },
  "request": {
    "method": "GET",
    "path": "/users/42"
  }
}

Key Metrics to Monitor

Apply RED (Rate, Errors, Duration) metrics to your exception handling pipeline:

MetricDescriptionUnit
Request RateNumber of requests handledRequests/sec
Error RateNumber of 4xx / 5xx responsesErrors/sec
Request DurationLatency of exception handling (TryHandleAsync)Milliseconds

Also consider USE (Utilization, Saturation, Errors) for system resources supporting the app.

Distributed Tracing (OpenTelemetry .NET Example)

Instrument your app with OpenTelemetry to trace exceptions across services:

builder.Services.AddOpenTelemetryTracing(tracerProviderBuilder =>
{
    tracerProviderBuilder
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddConsoleExporter();
});

Insert correlation ID into logs and trace spans:

public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
{
    var correlationId = context.TraceIdentifier; // Or from your correlation middleware

    using var activity = new Activity("ExceptionHandling").Start();
    activity.SetTag("exception.type", exception.GetType().FullName);
    activity.SetTag("exception.message", exception.Message);
    activity.SetTag("correlationId", correlationId);

    // Proceed with logging and response
}

SLI / SLO / Alerting Reference Table

SLISLOAlert Condition
% of requests with 5xx errors<1% over 5 minutesMore than 0.5% 5xx errors in 1 minute
Average request duration<200msRequest latency exceeds 500ms for >5% of requests
Logging correlation failures0 eventsMissing correlation ID in >1% of logs

Deep Dive: How IExceptionHandler Works Internally in ASP.NET Core Pipeline

The IExceptionHandler interface is a new abstraction introduced in ASP.NET Core 8 that integrates tightly with the request processing middleware pipeline to provide global exception handling. Understanding its internal mechanics helps design robust and performant handlers.

Middleware Integration and Flow Control

The core integration happens inside the UseExceptionHandler() middleware. When you register this middleware early in the pipeline, it wraps downstream components like so:

  • The middleware invokes the next delegate in the pipeline inside a try/catch block.
  • If no exception occurs, the request proceeds normally.
  • If an exception is thrown, it is caught by this middleware.

Once the exception is caught:

  1. The middleware iterates over all IExceptionHandler implementations registered in the service container, in registration order.

  2. For each handler, it calls the TryHandleAsync() method, passing the current HttpContext, the caught exception, and an optional CancellationToken.

  3. If TryHandleAsync() returns true, the middleware treats the exception as handled and short-circuits further propagation, writing the response configured by the handler.

  4. If false is returned, the middleware tries the next handler in the chain.

  5. If all handlers return false, the middleware resorts to a fallback behavior (usually rethrowing or producing a minimal error response).

What Happens After Handling?

When a handler returns true, it must ensure the HttpResponse body and headers are in a valid terminal state:

  • The HTTP status code should be set to an appropriate error code.
  • Headers must be flushed correctly to avoid partial responses.
  • The response content type typically should be set to "application/problem+json" to align with RFC 7807 standards.
  • The response body contains serialized error details.

The middleware then completes the request without re-throwing the exception, effectively ending the pipeline.

Cancellation Token and Async Considerations

The CancellationToken parameter passed to TryHandleAsync() allows handlers to respect client disconnects or server shutdown signals, making sure heavy logging or response buffering does not continue unnecessarily.

Given that exception handling is latency-sensitive, async APIs are critical: performing I/O such as logging to remote sinks or serializing the response without blocking threads is essential.

ExceptionHandler vs UseExceptionHandler()

IExceptionHandler is just the interface. The key piece that wires this into the ASP.NET Core request pipeline is the UseExceptionHandler() middleware, which loads and invokes all registered handlers.

This separation ensures:

  • One middleware instance manages the lifecycle and exception catching.
  • Multiple handlers compose to cover different exception categories or responsibilities, improving modularity.

Worked Production Scenario: Handling Transient Failures and Circuit Breakers

Handling exceptions globally is not just about mapping exceptions to HTTP status codes; it often involves integrating resilience patterns like retries and circuit breakers for infrastructure calls.

Let's walk through a realistic scenario in a .NET 8 Web API where a downstream HTTP call to a remote service might fail transiently.

Scenario Setup

  • The Web API calls a remote microservice via HttpClient.
  • Transient errors (e.g., HTTP 503 or timeouts) are retried with Polly.
  • If retries fail, a RemoteServiceUnavailableException is thrown.
  • Global exception handling transforms this into an HTTP 503 response to clients.
  • Circuit breaker trip events are logged for observability.

Domain Exception Definition

public sealed class RemoteServiceUnavailableException : DomainException
{
    public RemoteServiceUnavailableException(string message) : base(message) { }
}

Polly Retry and Circuit Breaker Policy

Configure transient-fault-handling policies during DI registration:

builder.Services.AddHttpClient("RemoteService")
    .AddPolicyHandler(Policy<HttpResponseMessage>
        .Handle<HttpRequestException>()
        .OrResult(msg => msg.StatusCode == HttpStatusCode.ServiceUnavailable)
        .RetryAsync(3)) // retry 3 times
    .AddPolicyHandler(Policy<HttpResponseMessage>
        .Handle<HttpRequestException>()
        .OrResult(msg => msg.StatusCode == HttpStatusCode.ServiceUnavailable)
        .CircuitBreakerAsync(
            exceptionsAllowedBeforeBreaking: 2,
            durationOfBreak: TimeSpan.FromMinutes(1),
            onBreak: (outcome, timespan) =>
            {
                // Log the circuit breaker open event globally
                var logger = builder.Services.BuildServiceProvider().GetRequiredService<ILogger<Program>>();
                logger.LogWarning("Circuit breaker opened due to {Outcome}, breaking for {Timespan}", outcome, timespan);
            }));

Throwing Domain Exception on Failure

A typed HTTP client could throw the domain exception:

public class RemoteServiceClient
{
    private readonly HttpClient _httpClient;

    public RemoteServiceClient(IHttpClientFactory factory)
        => _httpClient = factory.CreateClient("RemoteService");

    public async Task<string> GetDataAsync(CancellationToken ct)
    {
        var response = await _httpClient.GetAsync("/data", ct);
        if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
            throw new RemoteServiceUnavailableException("Remote service is currently unavailable");
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync(ct);
    }
}

Exception Handler Enhancements

Extend your global or domain exception handler to recognize this new exception:

public sealed class DomainExceptionHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception ex, CancellationToken ct)
    {
        if (ex is RemoteServiceUnavailableException)
        {
            context.Response.StatusCode = 503;
            context.Response.ContentType = "application/problem+json";

            var problemDetails = new ProblemDetails
            {
                Status = 503,
                Title = "Service Unavailable",
                Detail = ex.Message,
                Instance = $"{context.Request.Method} {context.Request.Path}",
                Extensions = { ["retryAfter"] = 60 } // seconds to retry suggested
            };

            await context.Response.WriteAsJsonAsync(problemDetails, ct);
            return true;
        }
        // fallback logic omitted
        return false;
    }
}

Observability Points

  • Log circuit breaker openings with batch size and timestamps.
  • Capture exceptions, including retries exhausted and final failures.
  • Track the number of remote calls, success/error rates, and latency.

This example demonstrates how domain exceptions can be extended to cover resilience concerns, and how IExceptionHandler enables clean, centralized translation of these failures into API responses.


Edge Cases and Failure Modes in IExceptionHandler Usage

Even with straightforward design, production exceptions often break assumptions. Prepare for edge cases:

1. Exceptions While Writing the Response

If an exception occurs inside TryHandleAsync() while setting status code or writing the ProblemDetails JSON, the system can enter a failure loop or produce incomplete responses.

Mitigation:

  • Wrap your handler logic in a try/catch block.
  • On error, fallback to a minimal plain-text 500 response.
  • Log the internal failure in detail.

Example:

public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
{
    try
    {
        // Main exception handling logic
    }
    catch (Exception handlerEx)
    {
        // Fallback response
        context.Response.Clear();
        context.Response.StatusCode = 500;
        context.Response.ContentType = "text/plain";
        await context.Response.WriteAsync("An error occurred processing the error response.", ct);
        
        // Log handler error but do NOT rethrow
        _logger.LogCritical(handlerEx, "Exception in exception handler");
        return true;
    }
}

2. Exception Loop / Recursion

Avoid throwing exceptions inside your handler or inside logging logic that the handler depends on, as this can cause infinite loops.

Mitigation:

  • Use logging sinks that are reliable and don’t throw exceptions.
  • Catch all exceptions inside your handler method.
  • Set guard flags in context.Items or static variables to detect recursive error handling calls.

3. Long-Running Handlers and Cancellation

Heavy operations, such as remote logging or error report submission, can delay response writing or block thread pool resources.

Mitigation:

  • Respect the provided CancellationToken.
  • Offload heavy tasks to background queues if possible.
  • Use asynchronous APIs with timeouts.

4. Partial Writes and Connection Aborts

The client may disconnect during error response transmission (client abort). ASP.NET Core might close the socket midway.

Mitigation:

  • Check HttpContext.RequestAborted token and cancel work early.
  • Set response headers before writing body to ensure status code is sent.
  • Avoid complex streaming or chunked responses in error handlers.

5. Return Status Code Conflicts

Other middlewares or endpoints might have partially set response status codes or headers before the exception.

Mitigation:

  • Call HttpResponse.Clear() early in the handler to reset headers and buffers safely.
  • Ensure your handler always writes a fresh response.

Performance Considerations and Optimizations

Global exception handling must be efficient, especially under load when failures spike.

Key Performance Factors

  • Serialization: WriteAsJsonAsync calls need to be fast and allocate minimal memory. Use System.Text.Json with precompiled serializers if possible.
  • Logging: Logging stack traces and structured data can be expensive. Use asynchronous, non-blocking logging sinks.
  • Handler chaining: Multiple handlers will add latency; minimize the number and complexity of handlers.
  • Exception generation: Avoid creating verbose exceptions with large stack traces or heavy messages when possible.
  • Cancellation: Honor CancellationToken to prevent work for aborted clients.

Measuring and Optimizing

Use benchmarking tools like BenchmarkDotNet or custom load tests to measure:

  • The average latency added by TryHandleAsync() calls.
  • Memory allocations during serialization and logging.
  • Impact on thread pool and request throughput under error conditions.

Example optimization:

// Use source-gen for Json serialization with ProblemDetails
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
await context.Response.WriteAsJsonAsync(problemDetails, options, ct);

Avoid Over-Logging in High-Load Failures

If thousands of requests fail simultaneously, excessive logging and error response serialization might overwhelm resources.

Mitigate with:

  • Sampling logs and metrics.
  • Circuit breakers on telemetry sinks.
  • Rate-limiting response details or switching to minimal error payloads.

Decision Checklist: When and How to Use IExceptionHandler

Before adopting or designing your global exception handling strategy using IExceptionHandler, ask yourself:

QuestionConsiderations
Is your project on .NET 8 or higher?IExceptionHandler is only available starting with .NET 8+.
Do you have multiple logical exception categories?If yes, chaining handlers is ideal to isolate concerns (domain vs infrastructure).
Are you using ProblemDetails for error responses?Built-in integration with UseExceptionHandler() streamlines consistent RFC 7807 responses.
Do you want to avoid try/catch in controllers?Centralized handlers reduce boilerplate and increase consistency.
Do you need fine-grained control over exception translation?Use domain exceptions mapped to status codes in handlers.
Will performance overhead of multiple handlers be acceptable?Minimize handlers to improve latency under failure.
Is your logging and telemetry setup ready?Ensure correlation IDs and structured logs are emitted from within handlers.
Do you need fallback for unexpected exceptions?Always include a catch-all handler to avoid unhandled exceptions crashing your app.
Do you handle exception throw inside handler itself?Add defensive try/catch to prevent handler failure loops.

Observability Extension: Implementing Distributed Tracing Span in IExceptionHandler

To enable seamless tracing of error flows across microservices with OpenTelemetry, inject TracerProvider or use System.Diagnostics.Activity.

Example: Creating a Trace Span Around Exception Handling

using System.Diagnostics;

public sealed class TracingExceptionHandler : IExceptionHandler
{
    private readonly ILogger<TracingExceptionHandler> _logger;

    public TracingExceptionHandler(ILogger<TracingExceptionHandler> logger)
        => _logger = logger;

    public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
    {
        using var activity = new Activity("ExceptionHandling").Start();

        activity.SetTag("exception.type", exception.GetType().FullName);
        activity.SetTag("exception.message", exception.Message);
        activity.SetTag("http.method", context.Request.Method);
        activity.SetTag("http.path", context.Request.Path);
        activity.SetTag("correlationId", context.TraceIdentifier);

        _logger.LogError(exception, "Exception handled with correlationId {CorrelationId}", context.TraceIdentifier);

        // Delegate actual error response creation:
        // For example:
        context.Response.StatusCode = 500;
        context.Response.ContentType = "application/problem+json";
        var problem = new ProblemDetails
        {
            Status = 500,
            Title = "Internal Server Error",
            Detail = "An unexpected error occurred",
            Instance = $"{context.Request.Method} {context.Request.Path}",
            Extensions = { ["correlationId"] = context.TraceIdentifier }
        };

        await context.Response.WriteAsJsonAsync(problem, ct);

        return true;
    }
}

Register OpenTelemetry tracing in Program.cs:

builder.Services.AddOpenTelemetryTracing(tracerProviderBuilder =>
{
    tracerProviderBuilder
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddConsoleExporter();
});

This design ensures exception handling is visualized in distributed traces, correlating error events with upstream calls.


By understanding the internals, pitfalls, and production scenarios of IExceptionHandler, senior engineers can build robust, extensible global exception handling that integrates elegantly with observability frameworks and resilience policies in modern .NET 8 Web APIs.

Summary and Best Practices

  • Prefer <mark class="hl-amber">IExceptionHandler</mark> in .NET 8 to centralize and standardize exception handling in Web APIs.
  • Integrate with RFC 7807 ProblemDetails for clear, consumable error payloads.
  • Use domain exceptions to map business errors to HTTP status codes explicitly.
  • Never expose raw exception messages or stack traces in client responses for 500 errors.
  • Always log exceptions with full stack traces and correlation IDs to aid troubleshooting.
  • Chain multiple handlers if necessary for clear separation of concerns.
  • Instrument logs and telemetry with correlation IDs and OpenTelemetry to enable distributed tracing.
  • Monitor RED/USE metrics and define SLOs and alerts to keep your API reliable.

Centralized exception handling is not just about catching errors — it’s about controlling the user experience, hardening your API’s security posture, and improving operational observability.


Minimal Working Example for Quick Testing

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();
app.UseExceptionHandler();

app.MapGet("/error", () => throw new NotFoundException("User", 123));

app.Run();

public sealed class GlobalExceptionHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
    {
        context.Response.StatusCode = 500;
        context.Response.ContentType = "application/problem+json";
        await context.Response.WriteAsJsonAsync(new ProblemDetails
        {
            Status = 500,
            Title = "Error",
            Detail = "An error occurred."
        }, ct);
        return true;
    }
}

public class NotFoundException : Exception
{
    public NotFoundException(string type, object id) : base($"{type} {id} not found") { }
}

This minimal example demonstrates the bare minimum to return a JSON error response globally.


Realistic Usage with Domain Exception and Logging

public sealed class GlobalExceptionHandler : IExceptionHandler
{
    private readonly ILogger<GlobalExceptionHandler> _logger;

    public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
        => _logger = logger;

    public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
    {
        var correlationId = context.TraceIdentifier;
        _logger.LogError(exception, "Unhandled exception. CorrelationId: {CorrelationId}", correlationId);

        int statusCode = exception switch
        {
            NotFoundException => 404,
            ValidationException => 422,
            _ => 500
        };

        var problem = new ProblemDetails
        {
            Status = statusCode,
            Title = statusCode == 500 ? "Internal server error" : "Error",
            Detail = statusCode == 500 ? "An unexpected error occurred" : exception.Message,
            Instance = $"{context.Request.Method} {context.Request.Path}",
            Extensions = { ["correlationId"] = correlationId }
        };

        context.Response.StatusCode = statusCode;
        context.Response.ContentType = "application/problem+json";
        await context.Response.WriteAsJsonAsync(problem, ct);

        return true;
    }
}

This realistic example handles domain exceptions differently from unexpected ones and logs with correlation ID.


By adopting these techniques, you will build resilient and maintainable Web APIs using the latest .NET 8 exception handling capabilities.