Advertisement
Intermediate ASP.NET Core, Error Handling

How do you map different custom exception types to different HTTP status codes in a global exception handler?

Short answer

Inside your exception handler, inspect the caught exception's type (or a custom base exception hierarchy) and map it to the semantically correct HTTP status code -- a NotFoundException maps to 404, a ValidationException to 400, an UnauthorizedAccessException to 403 -- rather…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Inside your exception handler, inspect the caught exception's type (or a custom base exception hierarchy) and map it to the semantically correct HTTP status code -- 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"),
            _ => (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