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.

ExceptionHandlingMiddleware.cs 2.0KB

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