| | | 1 | | using Microsoft.Extensions.Options; |
| | | 2 | | |
| | | 3 | | namespace ZhEaIsNsAaBn.Utilities.APIExceptionHandlers; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Handles failed calls to other services: <see cref="HttpRequestException"/> → <c>BadGateway</c> (default 502), |
| | | 7 | | /// <see cref="TaskCanceledException"/> (a timeout) → <c>GatewayTimeout</c> (default 504). Category: <c>ExternalService< |
| | | 8 | | /// A request the client aborted never gets here: ASP.NET Core's exception middleware answers 499 itself. |
| | | 9 | | /// </summary> |
| | | 10 | | public sealed class ExternalServiceExceptionHandler : BaseExceptionHandler<ExternalServiceExceptionHandler>, IExceptionH |
| | | 11 | | { |
| | | 12 | | private const string Category = "ExternalService"; |
| | | 13 | | |
| | | 14 | | |
| | | 15 | | /// <summary>Creates the handler.</summary> |
| | | 16 | | /// <param name="logger">The logger.</param> |
| | | 17 | | /// <param name="environment">The host environment; Development adds the HTTP error text.</param> |
| | | 18 | | /// <param name="settings">The status mapping.</param> |
| | | 19 | | public ExternalServiceExceptionHandler( ILogger<ExternalServiceExceptionHandler> logger, IWebHostEnvironment environ |
| | 192 | 20 | | : base( logger, environment, settings ) { } |
| | | 21 | | |
| | | 22 | | |
| | | 23 | | /// <inheritdoc /> |
| | | 24 | | public async ValueTask<bool> TryHandleAsync( HttpContext httpContext, Exception exception, CancellationToken cancell |
| | | 25 | | { |
| | 64 | 26 | | ArgumentNullException.ThrowIfNull( httpContext ); |
| | | 27 | | |
| | 64 | 28 | | Error? error = exception switch |
| | 64 | 29 | | { |
| | 8 | 30 | | HttpRequestException http => new Error( "BadGateway", Category, "خدمة خارجية غير متاحة حا |
| | 8 | 31 | | "An external service is currently unavailable. Pl |
| | 8 | 32 | | + ( Environment.IsDevelopment() ? $" HTTP Error: |
| | 4 | 33 | | TaskCanceledException => new Error( "GatewayTimeout", Category, "انتهت مهلة الطلب أثناء ا |
| | 4 | 34 | | "The request timed out while waiting for an external |
| | 52 | 35 | | _ => null |
| | 64 | 36 | | }; |
| | | 37 | | |
| | 116 | 38 | | if ( error is null ) { return false; } |
| | | 39 | | |
| | | 40 | | |
| | 12 | 41 | | Log.ExternalServiceError( Logger, exception, httpContext.Request.Path, httpContext.Request.Method, httpContext.T |
| | | 42 | | |
| | | 43 | | |
| | 12 | 44 | | await GenerateError( httpContext, error, cancellationToken ).ConfigureAwait( false ); |
| | | 45 | | |
| | 12 | 46 | | return true; |
| | 64 | 47 | | } |
| | | 48 | | } |