ExceptionMiddlewareExtensions.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System.Net;
  2. using Microsoft.AspNetCore.Diagnostics;
  3. using Newtonsoft.Json;
  4. using Newtonsoft.Json.Serialization;
  5. using Products.Common.Dtos;
  6. using Products.Common.Exceptions;
  7. namespace Products.API.Middlewares
  8. {
  9. public static class ExceptionMiddlewareExtensions
  10. {
  11. public static void ConfigureExceptionHandler(this IApplicationBuilder app)
  12. {
  13. app.UseExceptionHandler(appError =>
  14. {
  15. appError.Run(async context =>
  16. {
  17. var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
  18. context.Response.StatusCode = GetErrorCode(contextFeature?.Error);
  19. context.Response.ContentType = "application/json";
  20. var errorDto = new ErrorResponseDto
  21. {
  22. StatusCode = context.Response.StatusCode
  23. };
  24. var json = JsonConvert.SerializeObject(errorDto,
  25. new JsonSerializerSettings
  26. {
  27. ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() },
  28. Formatting = Formatting.Indented
  29. });
  30. await context.Response.WriteAsync(json);
  31. });
  32. });
  33. }
  34. private static int GetErrorCode(Exception? exception)
  35. {
  36. return exception switch
  37. {
  38. // TODO: handle all the possible codes returned by the app
  39. RecordNotFoundException _ => (int)HttpStatusCode.NotFound,
  40. _ => (int)HttpStatusCode.InternalServerError
  41. };
  42. }
  43. }
  44. }