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.

ExceptionHandlingMiddleware.cs 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using AutoMapper;
  2. using Diligent.WebAPI.Host.Exceptions;
  3. using System.Net;
  4. namespace Diligent.WebAPI.Host.Middlewares
  5. {
  6. public class ExceptionHandlingMiddleware
  7. {
  8. private readonly RequestDelegate _next;
  9. private readonly ILogger<ExceptionHandlingMiddleware> _logger;
  10. public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
  11. {
  12. _next = next;
  13. _logger = logger;
  14. }
  15. public async Task InvokeAsync(HttpContext httpContext)
  16. {
  17. try
  18. {
  19. await _next(httpContext);
  20. }
  21. catch (Exception ex)
  22. {
  23. await HandleExceptionAsync(httpContext, ex);
  24. }
  25. }
  26. private async Task HandleExceptionAsync(HttpContext context, Exception ex)
  27. {
  28. context.Response.ContentType = "application/json";
  29. context.Response.StatusCode = ex switch
  30. {
  31. NotFoundException => (int)HttpStatusCode.NotFound,
  32. KeyNotFoundException => (int)HttpStatusCode.NotFound,
  33. BadHttpRequestException => (int)HttpStatusCode.BadRequest,
  34. //...
  35. _ => (int)HttpStatusCode.InternalServerError
  36. };
  37. _logger.LogError(ex.Message);
  38. await context.Response.WriteAsync(new ErrorDetails()
  39. {
  40. StatusCode = context.Response.StatusCode,
  41. Message = ex.Message
  42. }.ToString());
  43. }
  44. }
  45. }