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 2.1KB

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