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.
This commit is contained in:
Developer 02 2025-05-19 15:06:24 +02:00
parent f586e9eb2f
commit 14013bc7b7

View File

@ -7,6 +7,7 @@ namespace DigitalData.Core.Exceptions.Middleware;
public record HttpExceptionHandler(Type ExceptionType, Func<HttpContext, Exception, ILogger?, Task> HandleExceptionAsync) public record HttpExceptionHandler(Type ExceptionType, Func<HttpContext, Exception, ILogger?, Task> HandleExceptionAsync)
{ {
#region Alternative generator methods
public static HttpExceptionHandler Create<TException>(Func<HttpContext, Exception, ILogger?, Task> HandleExceptionAsync) where TException : Exception public static HttpExceptionHandler Create<TException>(Func<HttpContext, Exception, ILogger?, Task> HandleExceptionAsync) where TException : Exception
=> new HttpExceptionHandler(typeof(TException), HandleExceptionAsync); => new HttpExceptionHandler(typeof(TException), HandleExceptionAsync);
@ -20,10 +21,22 @@ public record HttpExceptionHandler(Type ExceptionType, Func<HttpContext, Excepti
await context.Response.WriteAsync(JsonSerializer.Serialize(new { message })); await context.Response.WriteAsync(JsonSerializer.Serialize(new { message }));
} }
); );
#endregion
#region Default handlers
public static readonly Func<Exception, string> DefaultMessageFactory = ex => ex.Message; public static readonly Func<Exception, string> DefaultMessageFactory = ex => ex.Message;
public static readonly HttpExceptionHandler DefaultBadRequest = Create<BadRequestException>(HttpStatusCode.BadRequest, DefaultMessageFactory); public static readonly HttpExceptionHandler DefaultBadRequest = Create<BadRequestException>(HttpStatusCode.BadRequest, DefaultMessageFactory);
public static readonly HttpExceptionHandler DefaultNotFound = Create<NotFoundException>(HttpStatusCode.NotFound, DefaultMessageFactory); public static readonly HttpExceptionHandler DefaultNotFound = Create<NotFoundException>(HttpStatusCode.NotFound, DefaultMessageFactory);
public static readonly HttpExceptionHandler Default = Create<Exception>(
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
}; };