選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

LuExceptionMiddleware.cs 2.2KB

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