Guest User

Untitled

a guest
Aug 8th, 2024
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.90 KB | None | 0 0
  1. ublic static class WebApplicationExtensions
  2. {
  3. public static IServiceCollection AddServices(this IServiceCollection services, IConfiguration configuration)
  4. {
  5. /*Some code*/
  6.  
  7. Log.Logger.Information("WebApplicationExtensions->AddServices->AddProblemDetails");
  8. services.AddProblemDetails(configuration);
  9.  
  10. return services;
  11. }
  12.  
  13.  
  14. private static void AddProblemDetails(this IServiceCollection services, IConfiguration configuration)
  15. {
  16. services.AddProblemDetails(options =>
  17. {
  18. options.ValidationProblemStatusCode = StatusCodes.Status400BadRequest;
  19.  
  20. options.Map<ProblemControllerException>(exception => new DetailedProblem(exception.error.Code, exception.error.Message)
  21. {
  22.  
  23. Detail = exception.HResult.ToString(),
  24. Title = exception.Message,
  25. Type = $"https://httpstatuses.io/{exception.statusCode}",
  26. Status = exception.statusCode
  27. });
  28.  
  29. options.Map<ProblemServiceException>(exception => new DetailedProblem(exception.error.Code, exception.error.Message)
  30. {
  31.  
  32. Detail = exception.HResult.ToString(),
  33. Title = exception.Message,
  34. Type = $"https://httpstatuses.io/{exception.statusCode}",
  35. Status = exception.statusCode
  36. });
  37.  
  38. options.Map<ProblemFluentValidationException>(exception => new DetailedProblem(exception.errors)
  39. {
  40. Detail = exception.HResult.ToString(),
  41. Title = string.IsNullOrEmpty(exception.Message) ? "" : exception.Message,
  42. Type = $"https://httpstatuses.io/{exception.statusCode}",
  43. Status = exception.statusCode
  44. });
  45.  
  46. options.Map<System.Exception>(exception => new DetailedProblem(ErrorsType.EMUN5000006.GetDisplayName(), "Internal server error")
  47. {
  48. Detail = exception.Message,
  49. Title = "Internal server error",
  50. Type = exception.GetType().Name,
  51. Status = (int)HttpStatusCode.InternalServerError
  52. });
  53.  
  54. options.OnBeforeWriteDetails = (ctx, problem) =>
  55. {
  56. var id = ctx.Request.GetHttpHeadersKey(configuration["ID_HEADER_KEY"]);
  57.  
  58. if (problem is ProblemDetailsBase pdb)
  59. {
  60. pdb.Id = id;
  61. }
  62.  
  63. problem.Instance = ctx.Request.Path;
  64. };
  65. options.IncludeExceptionDetails = (ctx, ex) =>
  66. {
  67. return false;
  68. };
  69. });
  70.  
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment