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.

LuExceptionMiddleware.cs 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Threading.Tasks;
  3. using Luticate2.Utils.Controllers;
  4. using Luticate2.Utils.Dbo.Basic;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.Extensions.Logging;
  7. using Newtonsoft.Json;
  8. namespace Luticate2.Utils.Middlewares
  9. {
  10. public class LuExceptionMiddleware
  11. {
  12. private readonly RequestDelegate _next;
  13. private readonly ILogger<LuExceptionMiddleware> _logger;
  14. public LuExceptionMiddleware(RequestDelegate next, ILogger<LuExceptionMiddleware> logger)
  15. {
  16. _next = next;
  17. _logger = logger;
  18. }
  19. public async Task Invoke(HttpContext context)
  20. {
  21. try
  22. {
  23. await _next.Invoke(context);
  24. }
  25. catch (LuResultException e)
  26. {
  27. _logger.LogError(e.Result.PrivateDetails + "\n" + e.Result.PublicDetails + "\n" + e.StackTrace);
  28. var response = context.Response;
  29. response.ContentType = "application/json";
  30. response.StatusCode = e.Result.GetHttpCode();
  31. await response.WriteAsync(JsonConvert.SerializeObject(new LuApiWrapperDbo<object>
  32. {
  33. code = e.Result.GetHttpCode(),
  34. data = null,
  35. message = e.Result.PublicDetails ?? e.Result.GetHttpString(),
  36. Version = LuUtilsExtensions.Options.Version
  37. })).ConfigureAwait(false);
  38. }
  39. catch (Exception e)
  40. {
  41. _logger.LogError(e.ToString());
  42. var response = context.Response;
  43. response.ContentType = "application/json";
  44. response.StatusCode = 500;
  45. await response.WriteAsync(JsonConvert.SerializeObject(new LuApiWrapperDbo<object>
  46. {
  47. code = 500,
  48. data = null,
  49. message = "Internal Error",
  50. Version = LuUtilsExtensions.Options.Version
  51. })).ConfigureAwait(false);
  52. }
  53. }
  54. }
  55. }