From 730a318b56e7df9a2e05f94cad783b169e6ce8ea Mon Sep 17 00:00:00 2001 From: TekH Date: Thu, 21 Aug 2025 10:57:34 +0200 Subject: [PATCH] =?UTF-8?q?feat(ExceptionHandlingMiddleware):=20Hinzuf?= =?UTF-8?q?=C3=BCgen,=20um=20Ausnahmen=20global=20zu=20behandeln?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../EnvelopeGenerator.Web.csproj | 1 + .../Middleware/ExceptionHandlingMiddleware.cs | 84 +++++++++++++++++++ EnvelopeGenerator.Web/Program.cs | 3 + 3 files changed, 88 insertions(+) create mode 100644 EnvelopeGenerator.Web/Middleware/ExceptionHandlingMiddleware.cs diff --git a/EnvelopeGenerator.Web/EnvelopeGenerator.Web.csproj b/EnvelopeGenerator.Web/EnvelopeGenerator.Web.csproj index 765ac80c..51a822fb 100644 --- a/EnvelopeGenerator.Web/EnvelopeGenerator.Web.csproj +++ b/EnvelopeGenerator.Web/EnvelopeGenerator.Web.csproj @@ -2102,6 +2102,7 @@ + diff --git a/EnvelopeGenerator.Web/Middleware/ExceptionHandlingMiddleware.cs b/EnvelopeGenerator.Web/Middleware/ExceptionHandlingMiddleware.cs new file mode 100644 index 00000000..6d1ae2b7 --- /dev/null +++ b/EnvelopeGenerator.Web/Middleware/ExceptionHandlingMiddleware.cs @@ -0,0 +1,84 @@ +using DigitalData.Core.Exceptions; +using System.Net; +using System.Text.Json; + +namespace EnvelopeGenerator.Web.Middleware; + +//TODO: Fix and use DigitalData.Core.Exceptions.Middleware +/// +/// 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. +/// +[Obsolete("Use DigitalData.Core.Exceptions.Middleware")] +public class ExceptionHandlingMiddleware +{ + private readonly RequestDelegate _next; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The next middleware in the request pipeline. + /// The logger instance for logging exceptions. + public ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger) + { + _next = next; + _logger = 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 + })); + } +} diff --git a/EnvelopeGenerator.Web/Program.cs b/EnvelopeGenerator.Web/Program.cs index af747418..aa2dd259 100644 --- a/EnvelopeGenerator.Web/Program.cs +++ b/EnvelopeGenerator.Web/Program.cs @@ -17,6 +17,7 @@ using EnvelopeGenerator.Web.Sanitizers; using EnvelopeGenerator.Application.Contracts.Services; using EnvelopeGenerator.Web.Models.Annotation; using DigitalData.UserManager.DependencyInjection; +using EnvelopeGenerator.Web.Middleware; var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger(); logger.Info("Logging initialized!"); @@ -199,6 +200,8 @@ try var app = builder.Build(); + app.UseMiddleware(); + // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) {