| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- using System.Net;
- using System.Net.Mime;
- using System.Text.Json;
-
- namespace BlackRock.Reporting.API.Exceptions
- {
- public class ExceptionMiddleware
- {
- private readonly RequestDelegate _next;
- private readonly ILoggingBuilder _logger;
- public ExceptionMiddleware(RequestDelegate next, ILoggingBuilder logger)
- {
- _logger = logger;
- _next = next;
- }
- public async Task InvokeAsync(HttpContext httpContext)
- {
- try
- {
- await _next(httpContext);
- }
- catch (Exception ex)
- {
- //_logger.LogError($"Something went wrong: {ex}");
- await HandleExceptionAsync(httpContext, ex);
- }
- }
- private async Task HandleExceptionAsync(HttpContext context, Exception exception)
- {
- context.Response.ContentType = "application/json";
- context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
- await context.Response.WriteAsync(new Error()
- {
- StatusCode = (HttpStatusCode)context.Response.StatusCode,
- Title = "Internal Server Error from the custom middleware."
- }.ToString());
- }
- }
- public class ApplicationExceptionMiddlewareBase
- {
- private readonly RequestDelegate next;
- private readonly IExceptionHandler exceptionHandler;
- private readonly ILogger<ApplicationExceptionMiddleware> logger;
- public ApplicationExceptionMiddlewareBase(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));
- }
- }
- }
- }
- }
|