Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.Net;
  2. using System.Text.Json;
  3. using Serilog;
  4. namespace SecureSharing.Infrastructure.Middleware;
  5. public sealed class ExceptionHandlingMiddleware
  6. {
  7. private readonly RequestDelegate nextRequestDelegate;
  8. private IWebHostEnvironment environment;
  9. public ExceptionHandlingMiddleware(
  10. RequestDelegate nextRequestDelegate,
  11. IWebHostEnvironment environment
  12. )
  13. {
  14. this.nextRequestDelegate = nextRequestDelegate ?? throw new ArgumentNullException(nameof(nextRequestDelegate));
  15. this.environment = environment ?? throw new ArgumentNullException(nameof(environment));
  16. }
  17. public async Task Invoke(HttpContext context)
  18. {
  19. try
  20. {
  21. context.TraceIdentifier = Guid.NewGuid().ToString();
  22. await nextRequestDelegate(context);
  23. }
  24. catch (Exception ex)
  25. {
  26. await HandleGlobalExceptionAsync(context, ex);
  27. }
  28. }
  29. private async Task HandleGlobalExceptionAsync(HttpContext context, Exception ex)
  30. {
  31. try
  32. {
  33. await WriteResponseAsync(context, HttpStatusCode.InternalServerError,
  34. JsonSerializer.Serialize(ex.Message));
  35. }
  36. catch (Exception e)
  37. {
  38. await WriteResponseAsync(context, HttpStatusCode.InternalServerError,
  39. JsonSerializer.Serialize(e.Message));
  40. }
  41. var logger = new LoggerConfiguration()
  42. .MinimumLevel.Debug()
  43. .WriteTo.File(@"AppData\Errors\log-.log", rollingInterval: RollingInterval.Day)
  44. .CreateLogger();
  45. logger.Error(ex, "Unhandled Exception" /* - Detected UserId: {UserId}" /*, context.User.GetUserId()*/);
  46. }
  47. private async Task WriteResponseAsync(HttpContext context, HttpStatusCode code, string jsonResponse)
  48. {
  49. context.Response.ContentType = "application/json";
  50. context.Response.StatusCode = (int)code;
  51. await context.Response.WriteAsync(jsonResponse);
  52. }
  53. }