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 logger; public ApplicationExceptionMiddleware(RequestDelegate next,IExceptionHandler exceptionHandler,ILogger 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)); } } } } }