Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ApplicationExceptionMiddleware.cs 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using System.Net.Mime;
  2. using System.Text.Json;
  3. namespace BlackRock.Reporting.API.Exceptions
  4. {
  5. public class ApplicationExceptionMiddleware
  6. {
  7. private readonly RequestDelegate next;
  8. private readonly IExceptionHandler exceptionHandler;
  9. private readonly ILogger<ApplicationExceptionMiddleware> logger;
  10. public ApplicationExceptionMiddleware(RequestDelegate next,IExceptionHandler exceptionHandler,ILogger<ApplicationExceptionMiddleware> logger)
  11. {
  12. this.next = next;
  13. this.exceptionHandler = exceptionHandler;
  14. this.logger = logger;
  15. }
  16. public async Task InvokeAsync(HttpContext httpContext)
  17. {
  18. try
  19. {
  20. await next(httpContext);
  21. }
  22. catch (Exception ex)
  23. {
  24. var error = exceptionHandler.HandleException(ex);
  25. if(!httpContext.Response.HasStarted)
  26. {
  27. httpContext.Response.Clear();
  28. httpContext.Response.ContentType = MediaTypeNames.Application.Json;
  29. httpContext.Response.StatusCode = (int)error.StatusCode;
  30. await httpContext.Response.WriteAsync(JsonSerializer.Serialize(error));
  31. }
  32. }
  33. }
  34. }
  35. }