From 14013bc7b7a8bc97b937572d3b72124bf0226c80 Mon Sep 17 00:00:00 2001 From: Developer 02 Date: Mon, 19 May 2025 15:06:24 +0200 Subject: [PATCH] Add default handlers to HttpExceptionHandler Introduce static methods for creating HttpExceptionHandler instances for specific exceptions. Define default message factory and handlers for common HTTP status codes, including a generic handler that returns a JSON response for internal server errors. --- .../HttpExceptionHandler.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/DigitalData.Core.Exceptions.Middleware/HttpExceptionHandler.cs b/DigitalData.Core.Exceptions.Middleware/HttpExceptionHandler.cs index 817d04e..21a18c3 100644 --- a/DigitalData.Core.Exceptions.Middleware/HttpExceptionHandler.cs +++ b/DigitalData.Core.Exceptions.Middleware/HttpExceptionHandler.cs @@ -7,6 +7,7 @@ namespace DigitalData.Core.Exceptions.Middleware; public record HttpExceptionHandler(Type ExceptionType, Func HandleExceptionAsync) { + #region Alternative generator methods public static HttpExceptionHandler Create(Func HandleExceptionAsync) where TException : Exception => new HttpExceptionHandler(typeof(TException), HandleExceptionAsync); @@ -20,10 +21,22 @@ public record HttpExceptionHandler(Type ExceptionType, Func DefaultMessageFactory = ex => ex.Message; public static readonly HttpExceptionHandler DefaultBadRequest = Create(HttpStatusCode.BadRequest, DefaultMessageFactory); public static readonly HttpExceptionHandler DefaultNotFound = Create(HttpStatusCode.NotFound, DefaultMessageFactory); + + public static readonly HttpExceptionHandler Default = Create( + async (context, ex, logger) => + { + context.Response.ContentType = "application/json"; + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + var message = "An unexpected error occurred."; + await context.Response.WriteAsync(JsonSerializer.Serialize(new { message })); + }); + #endregion }; \ No newline at end of file