You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ExceptionMiddleware.cs 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System.Net;
  2. namespace BlackRock.Reporting.API.Exceptions
  3. {
  4. public class BRExceptionMiddleware
  5. {
  6. private readonly RequestDelegate _next;
  7. private readonly ILoggingBuilder _logger;
  8. public BRExceptionMiddleware(RequestDelegate next, ILoggingBuilder logger)
  9. {
  10. _logger = logger;
  11. _next = next;
  12. }
  13. public async Task InvokeAsync(HttpContext httpContext)
  14. {
  15. try
  16. {
  17. await _next(httpContext);
  18. }
  19. catch (Exception ex)
  20. {
  21. //_logger.LogError($"Something went wrong: {ex}");
  22. await HandleExceptionAsync(httpContext, ex);
  23. }
  24. }
  25. private async Task HandleExceptionAsync(HttpContext context, Exception exception)
  26. {
  27. context.Response.ContentType = "application/json";
  28. context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
  29. var message = exception switch
  30. {
  31. DomainException => "Access violation error from the custom middleware",
  32. _ => "Internal Server Error from the custom middleware."
  33. };
  34. await context.Response.WriteAsync(new Error()
  35. {
  36. StatusCode = (HttpStatusCode)context.Response.StatusCode,
  37. Title = message
  38. }.ToString());
  39. }
  40. }
  41. }