| 1234567891011121314151617181920212223242526272829303132333435363738 |
- using System.Net.Mime;
- using System.Text.Json;
-
- namespace BlackRock.Reporting.API.Exceptions
- {
- 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)
- {
- this.next = next;
- this.exceptionHandler = exceptionHandler;
- this.logger = logger;
- }
-
- public async Task InvokeAsync(HttpContext httpContext)
- {
- try
- {
- await next(httpContext);
- }
- catch (Exception ex)
- {
- var error = exceptionHandler.HandleException(ex);
- if(!httpContext.Response.HasStarted)
- {
- httpContext.Response.Clear();
- httpContext.Response.ContentType = MediaTypeNames.Application.Json;
- httpContext.Response.StatusCode = (int)error.StatusCode;
- await httpContext.Response.WriteAsync(JsonSerializer.Serialize(error));
- }
- }
- }
- }
- }
|