wasAsked.

Write a custom Middleware to Global Exception handling.

Capgemini · Full Stack Developer · technical

Published

Year not specified · .NET

Community answers

Posted by wasAsked editorial collection

In .NET 8 and later, the recommended approach is IExceptionHandler. Writing your own middleware is still a classic interview exercise, so here is a complete version. public sealed class GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger, IHostEnvironment env) { public async Task InvokeAsync(HttpContext context) { try { await next(context); } catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) { // client disconnected: nothing to send, not an error } catch (Exception ex) { logger.LogError(ex, "Unhandled exception for {Method} {Path}", context.Request.Method, context.Request.Path); if (context.Response.HasStarted) throw; // cannot change the response any more var (status, title) = ex switch { KeyNotFoundException => (StatusCodes.Status404NotFound, "Resource not found"), UnauthorizedAccessException => (StatusCodes.Status403Forbidden, "Forbidden"), ArgumentException => (StatusCodes.Status400BadRequest, "Invalid request"), _ => (StatusCodes.Status500InternalServerError, "An unexpected error occurred") }; var problem = new ProblemDetails { Status = status, Title = title, Detail = env.IsDevelopment() ? ex.Message : null, Instance = context.Request.Path }; problem.Extensions["traceId"] = Activity.Current?.Id ?? context.TraceIdentifier; context.Response.Clear(); context.Response.StatusCode = status; await context.Response.WriteAsJsonAsync(problem, options: null, contentType: "application/problem+json"); } } } // Program.cs — register first so it wraps everything else app.UseMiddleware<GlobalExceptionMiddleware>(); Points to explain: - It must be early in the pipeline so it catches exceptions from all later middleware and endpoints. - Check Response.HasStarted: once headers are sent, you cannot replace the response. - Never expose exception details or stack traces in production; return a traceId instead so logs can be found. - Use a consistent Problem Details format (RFC 7807) so frontends handle errors uniformly. - Prefer custom exception types (NotFoundException, ConflictException) mapped to status codes over generic framework exceptions. - Do not swallow exceptions silently, and do not treat client cancellations as server errors. - Unit-test it by invoking InvokeAsync with a DefaultHttpContext and a next delegate that throws. Modern equivalent: services.AddProblemDetails(); services.AddExceptionHandler<MyHandler>(); app.UseExceptionHandler();

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics