| 6 | namespace API.Middleware; |
| 7 | |
| 8 | public class ExceptionMiddleware(IHostEnvironment env, ILogger<ExceptionMiddleware> logger) |
| 9 | : IMiddleware |
| 10 | { |
| 11 | public async Task InvokeAsync(HttpContext context, RequestDelegate next) |
| 12 | { |
| 13 | try |
| 14 | { |
| 15 | await next(context); |
| 16 | } |
| 17 | catch (Exception ex) |
| 18 | { |
| 19 | await HandleException(context, ex); |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | private async Task HandleException(HttpContext context, Exception ex) |
| 24 | { |
| 25 | logger.LogError(ex, ex.Message); |
| 26 | context.Response.ContentType = "application/json"; |
| 27 | context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; |
| 28 | |
| 29 | var response = new ProblemDetails |
| 30 | { |
| 31 | Status = 500, |
| 32 | Detail = env.IsDevelopment() |
| 33 | ? ex.StackTrace?.ToString() |
| 34 | : null, |
| 35 | Title = ex.Message |
| 36 | }; |
| 37 | |
| 38 | var options = new JsonSerializerOptions |
| 39 | {PropertyNamingPolicy = JsonNamingPolicy.CamelCase}; |
| 40 | |
| 41 | var json = JsonSerializer.Serialize(response, options); |
| 42 | |
| 43 | await context.Response.WriteAsync(json); |
| 44 | } |
| 45 | } |
nothing calls this directly
no outgoing calls
no test coverage detected