| 3 | using System.Net; |
| 4 | |
| 5 | public class ExceptionMiddleware |
| 6 | { |
| 7 | private readonly RequestDelegate _next; |
| 8 | private readonly ILogger _logger; |
| 9 | |
| 10 | public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger) |
| 11 | { |
| 12 | _next = next; |
| 13 | _logger = logger; |
| 14 | } |
| 15 | |
| 16 | public async Task Invoke(HttpContext context) |
| 17 | { |
| 18 | try |
| 19 | { |
| 20 | await _next(context); |
| 21 | } |
| 22 | catch (TaskCanceledException) when (context.RequestAborted.IsCancellationRequested) |
| 23 | { |
| 24 | context.Response.StatusCode = 418; // I'm a teapot |
| 25 | } |
| 26 | catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) |
| 27 | { |
| 28 | context.Response.StatusCode = 418; // I'm a teapot |
| 29 | } |
| 30 | catch (BadHttpRequestException ex) when (context.RequestAborted.IsCancellationRequested || ex.StatusCode == (int)HttpStatusCode.RequestTimeout) |
| 31 | { |
| 32 | context.Response.StatusCode = 418; // I'm a teapot |
| 33 | } |
| 34 | #pragma warning disable CS0618 // Type or member is obsolete |
| 35 | catch (Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException) |
| 36 | { |
| 37 | context.Response.StatusCode = 418; // I'm a teapot |
| 38 | } |
| 39 | #pragma warning restore CS0618 // Type or member is obsolete |
| 40 | catch (HttpRequestException ex) |
| 41 | { |
| 42 | context.Response.StatusCode = (int)(ex.StatusCode ?? HttpStatusCode.InternalServerError); |
| 43 | |
| 44 | _logger.LogError(ex, "Dependency error on {Path}", context.Request.Path.Value); |
| 45 | } |
| 46 | catch (Microsoft.AspNetCore.Authentication.AuthenticationFailureException) |
| 47 | { |
| 48 | context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; |
| 49 | } |
| 50 | catch (Exception ex) |
| 51 | { |
| 52 | context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; |
| 53 | |
| 54 | _logger.LogError(ex, "Unexpected error on {Path}", context.Request.Path.Value); |
| 55 | } |
| 56 | } |
| 57 | } |
nothing calls this directly
no outgoing calls
no test coverage detected