How do you map different exception types to different HTTP status codes in a global exception handler?
Short answer
Inside your exception handler (whether the older UseExceptionHandler lambda or the newer IExceptionHandler), inspect the caught exception's type (or a custom base exception hierarchy your application defines) and map it to the semantically correct HTTP status code -- e.g., a…
Advertisement
AModel answer
Inside your exception handler (whether the older UseExceptionHandler lambda or the newer IExceptionHandler), inspect the caught exception's type (or a custom base exception hierarchy your application defines) and map it to the semantically correct HTTP status code -- e.g., a NotFoundException maps to 404, a ValidationException to 400, an UnauthorizedAccessException to 403 -- rather than defaulting every unhandled exception to a generic 500.
public class GlobalExceptionHandler : IExceptionHandler {
public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct) {
var (statusCode, title) = exception switch {
NotFoundException => (404, "Resource not found"),
ValidationException => (400, "Validation failed"),
UnauthorizedAccessException => (403, "Access denied"),
_ => (500, "An unexpected error occurred")
};
context.Response.StatusCode = statusCode;
await context.Response.WriteAsJsonAsync(new { title }, ct);
return true;
}
}Real-world example
An API's global handler correctly returns 404 for a custom ProductNotFoundException and 400 for a custom InvalidOrderStateException, giving API consumers semantically accurate status codes instead of a blanket 500 for every kind of failure.
Likely follow-ups
- What custom exception hierarchy design makes this mapping cleanest to maintain?
- Should business logic ever throw exceptions for expected failure cases, or use a Result pattern instead?
Related topics