| | | 1 | | using Microsoft.AspNetCore.Diagnostics; |
| | | 2 | | using Microsoft.AspNetCore.Mvc; |
| | | 3 | | |
| | | 4 | | namespace Api.Middleware; |
| | | 5 | | |
| | | 6 | | public sealed class GlobalExceptionHandler : IExceptionHandler { |
| | | 7 | | private readonly ILogger<GlobalExceptionHandler> _logger; |
| | | 8 | | private readonly IProblemDetailsService _problemDetailsService; |
| | | 9 | | |
| | 2 | 10 | | public GlobalExceptionHandler( |
| | 2 | 11 | | ILogger<GlobalExceptionHandler> logger, |
| | 4 | 12 | | IProblemDetailsService problemDetailsService) { |
| | 2 | 13 | | _logger = logger; |
| | 2 | 14 | | _problemDetailsService = problemDetailsService; |
| | 2 | 15 | | } |
| | | 16 | | |
| | | 17 | | public async ValueTask<bool> TryHandleAsync( |
| | | 18 | | HttpContext httpContext, |
| | | 19 | | Exception exception, |
| | 0 | 20 | | CancellationToken ct) { |
| | | 21 | | |
| | 0 | 22 | | var pd = new ProblemDetails { |
| | 0 | 23 | | Status = StatusCodes.Status500InternalServerError, |
| | 0 | 24 | | Title = "An unexpected error occurred.", |
| | 0 | 25 | | Detail = exception.Message, |
| | 0 | 26 | | Type = "server_error", |
| | 0 | 27 | | Instance = httpContext.Request.Path |
| | 0 | 28 | | }; |
| | | 29 | | |
| | 0 | 30 | | httpContext.Response.StatusCode = pd.Status!.Value; |
| | | 31 | | |
| | 0 | 32 | | var handled = await _problemDetailsService.TryWriteAsync( |
| | 0 | 33 | | new ProblemDetailsContext { |
| | 0 | 34 | | HttpContext = httpContext, |
| | 0 | 35 | | ProblemDetails = pd |
| | 0 | 36 | | }); |
| | | 37 | | |
| | 0 | 38 | | _logger.LogError(exception, "Unhandled exception."); |
| | | 39 | | |
| | 0 | 40 | | return handled; |
| | 0 | 41 | | } |
| | | 42 | | } |