Updated GlobalExceptionHandlerOptions to replace HttpExceptionMapping with HttpExceptionHandler. Removed HttpExceptionMapping class and introduced HttpExceptionHandler for managing exceptions in HTTP requests. Added methods for creating specific exception handlers and default handlers for common exceptions, with JSON serialization for error messages.
29 lines
1.4 KiB
C#
29 lines
1.4 KiB
C#
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Logging;
|
|
using System.Net;
|
|
using System.Text.Json;
|
|
|
|
namespace DigitalData.Core.Exceptions.Middleware;
|
|
|
|
public record HttpExceptionHandler(Type ExceptionType, Func<HttpContext, Exception, ILogger?, Task> HandleExceptionAsync)
|
|
{
|
|
public static HttpExceptionHandler Create<TException>(Func<HttpContext, Exception, ILogger?, Task> HandleExceptionAsync) where TException : Exception
|
|
=> new HttpExceptionHandler(typeof(TException), HandleExceptionAsync);
|
|
|
|
public static HttpExceptionHandler Create<TException>(HttpStatusCode statusCode, Func<Exception, string> messageFactory) where TException : Exception
|
|
=> Create<TException>(
|
|
async (context, ex, logger) =>
|
|
{
|
|
context.Response.ContentType = "application/json";
|
|
context.Response.StatusCode = (int)statusCode;
|
|
var message = messageFactory(ex);
|
|
await context.Response.WriteAsync(JsonSerializer.Serialize(new { 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 DefaultNotFound = Create<NotFoundException>(HttpStatusCode.NotFound, DefaultMessageFactory);
|
|
}; |