| | | 1 | | using ArturRios.Output; |
| | | 2 | | using ArturRios.Util.Http; |
| | | 3 | | using Microsoft.AspNetCore.Http; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | using Newtonsoft.Json; |
| | | 6 | | |
| | | 7 | | namespace ArturRios.Util.WebApi.Middleware; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Catches unhandled exceptions raised further down the pipeline and converts them into a JSON error response, |
| | | 11 | | /// logging the exception and quietly ignoring client-initiated request cancellations. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <param name="next">The next middleware in the pipeline.</param> |
| | | 14 | | /// <param name="logger">Used to log unhandled exceptions and cancellations.</param> |
| | 1 | 15 | | public class ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger) : WebApiMiddleware |
| | | 16 | | { |
| | | 17 | | /// <summary>Invokes the next middleware, catching any unhandled exception and writing an error response instead of |
| | | 18 | | /// <param name="httpContext">The current HTTP context.</param> |
| | | 19 | | public async Task InvokeAsync(HttpContext httpContext) |
| | 1 | 20 | | { |
| | | 21 | | try |
| | 1 | 22 | | { |
| | 1 | 23 | | await next(httpContext); |
| | 0 | 24 | | } |
| | 0 | 25 | | catch (OperationCanceledException oce) when (httpContext.RequestAborted.IsCancellationRequested) |
| | 0 | 26 | | { |
| | 0 | 27 | | logger.LogDebug("Request was canceled by the client: {OceMessage}", oce.Message); |
| | 0 | 28 | | } |
| | 0 | 29 | | catch (TaskCanceledException tce) when (httpContext.RequestAborted.IsCancellationRequested) |
| | 0 | 30 | | { |
| | 0 | 31 | | logger.LogDebug("Request was canceled by the client (TaskCanceled): {TceMessage}", tce.Message); |
| | 0 | 32 | | } |
| | 1 | 33 | | catch (Exception ex) |
| | 1 | 34 | | { |
| | 1 | 35 | | await HandleException(httpContext, ex); |
| | 1 | 36 | | } |
| | 1 | 37 | | } |
| | | 38 | | |
| | | 39 | | private async Task HandleException(HttpContext context, Exception exception) |
| | 1 | 40 | | { |
| | 1 | 41 | | if (context.RequestAborted.IsCancellationRequested || context.Response.HasStarted) |
| | 0 | 42 | | { |
| | 0 | 43 | | logger.LogDebug( |
| | 0 | 44 | | "Cannot write error response because the request was aborted or the response has already started."); |
| | | 45 | | |
| | 0 | 46 | | return; |
| | | 47 | | } |
| | | 48 | | |
| | 1 | 49 | | var messages = new[] { "Internal server error, please try again later" }; |
| | | 50 | | |
| | 1 | 51 | | if (exception is CustomException customException) |
| | 0 | 52 | | { |
| | 0 | 53 | | messages = customException.Messages; |
| | 0 | 54 | | } |
| | | 55 | | |
| | 1 | 56 | | logger.LogError(exception, "Unhandled exception while processing the request."); |
| | | 57 | | |
| | 1 | 58 | | context.Response.ContentType = "application/json"; |
| | 1 | 59 | | context.Response.StatusCode = HttpStatusCodes.InternalServerError; |
| | | 60 | | |
| | 1 | 61 | | var output = DataOutput<string>.New |
| | 1 | 62 | | .WithData(string.Empty) |
| | 1 | 63 | | .WithMessages(messages); |
| | | 64 | | |
| | 1 | 65 | | await context.Response.WriteAsync(JsonConvert.SerializeObject(output)); |
| | 1 | 66 | | } |
| | | 67 | | } |