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.

ApplicationExceptionMiddlewareBase.cs 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Net;
  2. using System.Net.Mime;
  3. using System.Text.Json;
  4. namespace BlackRock.Reporting.API.Exceptions
  5. {
  6. public class ExceptionMiddleware
  7. {
  8. private readonly RequestDelegate _next;
  9. private readonly ILoggingBuilder _logger;
  10. public ExceptionMiddleware(RequestDelegate next, ILoggingBuilder logger)
  11. {
  12. _logger = logger;
  13. _next = next;
  14. }
  15. public async Task InvokeAsync(HttpContext httpContext)
  16. {
  17. try
  18. {
  19. await _next(httpContext);
  20. }
  21. catch (Exception ex)
  22. {
  23. //_logger.LogError($"Something went wrong: {ex}");
  24. await HandleExceptionAsync(httpContext, ex);
  25. }
  26. }
  27. private async Task HandleExceptionAsync(HttpContext context, Exception exception)
  28. {
  29. context.Response.ContentType = "application/json";
  30. context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
  31. await context.Response.WriteAsync(new Error()
  32. {
  33. StatusCode = (HttpStatusCode)context.Response.StatusCode,
  34. Title = "Internal Server Error from the custom middleware."
  35. }.ToString());
  36. }
  37. }
  38. public class ApplicationExceptionMiddlewareBase
  39. {
  40. private readonly RequestDelegate next;
  41. private readonly IExceptionHandler exceptionHandler;
  42. private readonly ILogger<ApplicationExceptionMiddleware> logger;
  43. public ApplicationExceptionMiddlewareBase(RequestDelegate next, IExceptionHandler exceptionHandler, ILogger<ApplicationExceptionMiddleware> logger)
  44. {
  45. this.next = next;
  46. this.exceptionHandler = exceptionHandler;
  47. this.logger = logger;
  48. }
  49. public async Task InvokeAsync(HttpContext httpContext)
  50. {
  51. try
  52. {
  53. await next(httpContext);
  54. }
  55. catch (Exception ex)
  56. {
  57. var error = exceptionHandler.HandleException(ex);
  58. if (!httpContext.Response.HasStarted)
  59. {
  60. httpContext.Response.Clear();
  61. httpContext.Response.ContentType = MediaTypeNames.Application.Json;
  62. httpContext.Response.StatusCode = (int)error.StatusCode;
  63. await httpContext.Response.WriteAsync(JsonSerializer.Serialize(error));
  64. }
  65. }
  66. }
  67. }
  68. }