How does the IExceptionHandler interface (introduced in .NET 8) provide a more structured alternative to the UseExceptionHandler lambda approach?
Short answer
IExceptionHandler defines TryHandleAsync(HttpContext, Exception, CancellationToken), implemented as a proper, testable, DI-injectable class -- multiple exception handlers can be registered and are tried in order until one returns true, enabling different handlers for different…
Advertisement
AModel answer
IExceptionHandler defines TryHandleAsync(HttpContext, Exception, CancellationToken), implemented as a proper, testable, DI-injectable class -- multiple exception handlers can be registered and are tried in order until one returns true, enabling different handlers for different exception types in a clean, composable way rather than one large if/else chain in a single inline delegate.
public class ValidationExceptionHandler : IExceptionHandler {
public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct) {
if (exception is not ValidationException ve) return false;
context.Response.StatusCode = 400;
await context.Response.WriteAsJsonAsync(new { errors = ve.Errors }, ct);
return true;
}
}
builder.Services.AddExceptionHandler<ValidationExceptionHandler>();Real-world example
An API registers a specific ValidationExceptionHandler that formats validation errors distinctly, chained with a catch-all GlobalExceptionHandler for everything else, replacing what used to be a large if/else chain inside a single exception-handling lambda.
Likely follow-ups
- What determines the order multiple registered IExceptionHandlers are tried in?
- How does this integrate with ProblemDetails for standardized error responses?
Related topics