|
| 1 | +using System.Text.Json; |
| 2 | +using FluentValidation; |
| 3 | +using Microsoft.AspNetCore.Mvc; |
| 4 | +using Microsoft.EntityFrameworkCore; |
| 5 | + |
| 6 | +namespace Dotnet.Samples.AspNetCore.WebApi.Middlewares; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Middleware for global exception handling with RFC 7807 Problem Details format. |
| 10 | +/// </summary> |
| 11 | +public class ExceptionMiddleware(ILogger<ExceptionMiddleware> logger, IHostEnvironment environment) |
| 12 | +{ |
| 13 | + private const string ProblemDetailsContentType = "application/problem+json"; |
| 14 | + |
| 15 | + private static readonly JsonSerializerOptions JsonOptions = |
| 16 | + new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; |
| 17 | + |
| 18 | + /// <summary> |
| 19 | + /// Invokes the middleware to handle exceptions globally. |
| 20 | + /// </summary> |
| 21 | + public async Task InvokeAsync(HttpContext context, RequestDelegate next) |
| 22 | + { |
| 23 | + try |
| 24 | + { |
| 25 | + await next(context); |
| 26 | + } |
| 27 | + catch (Exception exception) |
| 28 | + { |
| 29 | + await HandleExceptionAsync(context, exception); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Handles the exception and returns an RFC 7807 compliant error response. |
| 35 | + /// </summary> |
| 36 | + private async Task HandleExceptionAsync(HttpContext context, Exception exception) |
| 37 | + { |
| 38 | + var (status, title) = MapExceptionToStatusCode(exception); |
| 39 | + |
| 40 | + var problemDetails = new ProblemDetails |
| 41 | + { |
| 42 | + Type = $"https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{status}", |
| 43 | + Title = title, |
| 44 | + Status = status, |
| 45 | + Detail = GetExceptionDetail(exception), |
| 46 | + Instance = context.Request.Path |
| 47 | + }; |
| 48 | + |
| 49 | + // Add trace ID for request correlation |
| 50 | + problemDetails.Extensions["traceId"] = context.TraceIdentifier; |
| 51 | + |
| 52 | + // codeql[cs/log-forging] Serilog structured logging automatically escapes control characters |
| 53 | + logger.LogError( |
| 54 | + exception, |
| 55 | + "Unhandled exception occurred. TraceId: {TraceId}, Path: {Path}, StatusCode: {StatusCode}", |
| 56 | + context.TraceIdentifier, |
| 57 | + context.Request.Path, |
| 58 | + status |
| 59 | + ); |
| 60 | + |
| 61 | + // Only modify response if headers haven't been sent yet |
| 62 | + if (!context.Response.HasStarted) |
| 63 | + { |
| 64 | + context.Response.StatusCode = status; |
| 65 | + context.Response.ContentType = ProblemDetailsContentType; |
| 66 | + |
| 67 | + await context.Response.WriteAsync( |
| 68 | + JsonSerializer.Serialize(problemDetails, JsonOptions) |
| 69 | + ); |
| 70 | + } |
| 71 | + else |
| 72 | + { |
| 73 | + logger.LogWarning( |
| 74 | + "Unable to write error response for TraceId: {TraceId}. Response has already started.", |
| 75 | + context.TraceIdentifier |
| 76 | + ); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + /// <summary> |
| 81 | + /// Maps exception types to appropriate HTTP status codes and titles. |
| 82 | + /// </summary> |
| 83 | + private static (int StatusCode, string Title) MapExceptionToStatusCode(Exception exception) |
| 84 | + { |
| 85 | + return exception switch |
| 86 | + { |
| 87 | + ValidationException => (StatusCodes.Status400BadRequest, "Validation Error"), |
| 88 | + ArgumentException |
| 89 | + or ArgumentNullException |
| 90 | + => (StatusCodes.Status400BadRequest, "Bad Request"), |
| 91 | + InvalidOperationException => (StatusCodes.Status400BadRequest, "Invalid Operation"), |
| 92 | + DbUpdateConcurrencyException => (StatusCodes.Status409Conflict, "Concurrency Conflict"), |
| 93 | + OperationCanceledException => (StatusCodes.Status408RequestTimeout, "Request Timeout"), |
| 94 | + _ => (StatusCodes.Status500InternalServerError, "Internal Server Error") |
| 95 | + }; |
| 96 | + } |
| 97 | + |
| 98 | + /// <summary> |
| 99 | + /// Gets the exception detail based on the environment. |
| 100 | + /// In Development: includes full exception details and stack trace. |
| 101 | + /// In Production: returns a generic message without sensitive information. |
| 102 | + /// </summary> |
| 103 | + private string GetExceptionDetail(Exception exception) |
| 104 | + { |
| 105 | + if (environment.IsDevelopment()) |
| 106 | + { |
| 107 | + return $"{exception.Message}\n\nStack Trace:\n{exception.StackTrace}"; |
| 108 | + } |
| 109 | + |
| 110 | + return exception switch |
| 111 | + { |
| 112 | + ValidationException => exception.Message, |
| 113 | + ArgumentException => exception.Message, |
| 114 | + _ => "An unexpected error occurred while processing your request." |
| 115 | + }; |
| 116 | + } |
| 117 | +} |
0 commit comments