From e5295b830243fab4df9d3eab1c51bc1cd5f2cc08 Mon Sep 17 00:00:00 2001 From: TekH Date: Thu, 9 Apr 2026 14:47:46 +0200 Subject: [PATCH] Add global exception handling middleware Introduced ExceptionHandlingMiddleware to handle exceptions across the ASP.NET Core request pipeline. The middleware logs exceptions and returns JSON error responses with appropriate HTTP status codes for BadRequestException (400), NotFoundException (404), and generic errors (500). Dependency injection is used for RequestDelegate and ILogger. --- .../Middleware/ExceptionHandlingMiddleware.cs | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 EnvelopeGenerator.ServiceHost/Middleware/ExceptionHandlingMiddleware.cs diff --git a/EnvelopeGenerator.ServiceHost/Middleware/ExceptionHandlingMiddleware.cs b/EnvelopeGenerator.ServiceHost/Middleware/ExceptionHandlingMiddleware.cs new file mode 100644 index 00000000..b16f2225 --- /dev/null +++ b/EnvelopeGenerator.ServiceHost/Middleware/ExceptionHandlingMiddleware.cs @@ -0,0 +1,75 @@ +namespace EnvelopeGenerator.ServiceHost.Middleware; + +using DigitalData.Core.Exceptions; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using System.Net; +using System.Text.Json; + +/// +/// Middleware for handling exceptions globally in the application. +/// Captures exceptions thrown during the request pipeline execution, +/// logs them, and returns an appropriate HTTP response with a JSON error message. +/// +/// +/// Initializes a new instance of the class. +/// +/// The next middleware in the request pipeline. +/// The logger instance for logging exceptions. +public class ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger) +{ + /// + /// Invokes the middleware to handle the HTTP request. + /// + /// The HTTP context of the current request. + /// A task that represents the asynchronous operation. + public async Task InvokeAsync(HttpContext context) + { + try + { + await next(context); // Continue down the pipeline + } + catch (Exception ex) + { + await HandleExceptionAsync(context, ex, logger); + } + } + + /// + /// Handles exceptions by logging them and writing an appropriate JSON response. + /// + /// The HTTP context of the current request. + /// The exception that occurred. + /// The logger instance for logging the exception. + /// A task that represents the asynchronous operation. + private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger logger) + { + context.Response.ContentType = "application/json"; + + string message; + + switch (exception) + { + case BadRequestException badRequestEx: + context.Response.StatusCode = (int)HttpStatusCode.BadRequest; + message = badRequestEx.Message; + break; + + case NotFoundException notFoundEx: + context.Response.StatusCode = (int)HttpStatusCode.NotFound; + message = notFoundEx.Message; + break; + + default: + logger.LogError(exception, "Unhandled exception occurred."); + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + message = "An unexpected error occurred."; + break; + } + + await context.Response.WriteAsync(JsonSerializer.Serialize(new + { + message + })); + } +} \ No newline at end of file