| | | 1 | | using ArturRios.Output; |
| | | 2 | | using ArturRios.Util.Http; |
| | | 3 | | using ArturRios.Util.WebApi.EndpointToggle; |
| | | 4 | | using ArturRios.Util.WebApi.Extensions; |
| | | 5 | | using Microsoft.AspNetCore.Http; |
| | | 6 | | using Microsoft.Extensions.Logging; |
| | | 7 | | |
| | | 8 | | namespace ArturRios.Util.WebApi.Middleware; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Catches unhandled exceptions raised further down the pipeline and converts them into a JSON error response, |
| | | 12 | | /// logging the exception and quietly ignoring client-initiated request cancellations. An |
| | | 13 | | /// <see cref="EndpointDisabledException"/> is answered with its own status code rather than 500. When the response |
| | | 14 | | /// has already started, the exception is rethrown so the server aborts the response instead of leaving the client |
| | | 15 | | /// with a truncated body that looks complete. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <param name="next">The next middleware in the pipeline.</param> |
| | | 18 | | /// <param name="logger">Used to log unhandled exceptions and cancellations.</param> |
| | 39 | 19 | | public class ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger) : WebApiMiddleware |
| | | 20 | | { |
| | | 21 | | private const string InternalServerError = "Internal server error, please try again later"; |
| | | 22 | | |
| | | 23 | | /// <summary>Invokes the next middleware, catching any unhandled exception and writing an error response instead of |
| | | 24 | | /// <param name="httpContext">The current HTTP context.</param> |
| | | 25 | | public async Task InvokeAsync(HttpContext httpContext) |
| | | 26 | | { |
| | | 27 | | try |
| | | 28 | | { |
| | 34 | 29 | | await next(httpContext); |
| | 24 | 30 | | } |
| | 0 | 31 | | catch (OperationCanceledException oce) when (httpContext.RequestAborted.IsCancellationRequested) |
| | | 32 | | { |
| | | 33 | | // TaskCanceledException derives from OperationCanceledException, so this covers both. |
| | 0 | 34 | | logger.LogDebug("Request was canceled by the client: {Message}", oce.Message); |
| | 0 | 35 | | } |
| | 10 | 36 | | catch (Exception ex) when (!httpContext.Response.HasStarted) |
| | | 37 | | { |
| | 9 | 38 | | await HandleException(httpContext, ex); |
| | | 39 | | } |
| | 33 | 40 | | } |
| | | 41 | | |
| | | 42 | | private async Task HandleException(HttpContext context, Exception exception) |
| | | 43 | | { |
| | 9 | 44 | | if (context.RequestAborted.IsCancellationRequested) |
| | | 45 | | { |
| | 0 | 46 | | logger.LogDebug(exception, "Cannot write an error response because the request was aborted."); |
| | | 47 | | |
| | 0 | 48 | | return; |
| | | 49 | | } |
| | | 50 | | |
| | | 51 | | int statusCode; |
| | | 52 | | string[] errors; |
| | | 53 | | |
| | | 54 | | switch (exception) |
| | | 55 | | { |
| | | 56 | | case EndpointDisabledException disabled: |
| | 1 | 57 | | logger.LogInformation("Request reached a disabled endpoint: {Path}", context.Request.Path); |
| | 1 | 58 | | statusCode = disabled.StatusCode; |
| | 1 | 59 | | errors = disabled.Messages; |
| | 1 | 60 | | break; |
| | | 61 | | case CustomException custom: |
| | 1 | 62 | | logger.LogError(exception, "Unhandled exception while processing the request."); |
| | 1 | 63 | | statusCode = HttpStatusCodes.InternalServerError; |
| | 1 | 64 | | errors = custom.Messages; |
| | 1 | 65 | | break; |
| | | 66 | | default: |
| | 7 | 67 | | logger.LogError(exception, "Unhandled exception while processing the request."); |
| | 7 | 68 | | statusCode = HttpStatusCodes.InternalServerError; |
| | 7 | 69 | | errors = [InternalServerError]; |
| | | 70 | | break; |
| | | 71 | | } |
| | | 72 | | |
| | | 73 | | // Errors, not messages: Success is computed from Errors, so a 500 whose text sat under Messages |
| | | 74 | | // came back with "success": true. AuthenticationMiddleware already envelopes its 401 this way. |
| | 9 | 75 | | var output = DataOutput<string>.New |
| | 9 | 76 | | .WithData(string.Empty) |
| | 9 | 77 | | .WithErrors(errors); |
| | | 78 | | |
| | 9 | 79 | | await context.Response.WriteOutputAsync(statusCode, output); |
| | 9 | 80 | | } |
| | | 81 | | } |