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