Created
April 18, 2021 20:28
-
-
Save ankitvijay/4fc273d5219ec2cd73e733ebdc2fd6ff to your computer and use it in GitHub Desktop.
Consistent Error Logging - Application Exception Middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Net.Mime; | |
| using System.Text.Json; | |
| using System.Threading.Tasks; | |
| using Microsoft.AspNetCore.Http; | |
| using Microsoft.Extensions.Logging; | |
| public class ApplicationExceptionMiddleware | |
| { | |
| private readonly RequestDelegate _next; | |
| private readonly IExceptionHandler _exceptionHandler; | |
| private readonly ILogger<ApplicationExceptionMiddleware> _logger; | |
| public ApplicationExceptionMiddleware( | |
| RequestDelegate next, | |
| IExceptionHandler exceptionHandler, | |
| ILogger<ApplicationExceptionMiddleware> logger) | |
| { | |
| _next = next; | |
| _exceptionHandler = exceptionHandler; | |
| _logger = logger; | |
| } | |
| public async Task InvokeAsync(HttpContext httpContext) | |
| { | |
| try | |
| { | |
| await _next(httpContext); | |
| } | |
| catch (Exception ex) | |
| { | |
| var errorDocument = _exceptionHandler.HandleException(ex); | |
| if (!httpContext.Response.HasStarted) | |
| { | |
| httpContext.Response.Clear(); | |
| httpContext.Response.ContentType = MediaTypeNames.Application.Json; | |
| httpContext.Response.StatusCode = (int) errorDocument.StatusCode; | |
| await httpContext.Response.WriteAsync(JsonSerializer.Serialize( | |
| errorDocument)); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment