LongExceptionCatch.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using Long.Core.Api;
  2. using Microsoft.AspNetCore.Http;
  3. using System.Net;
  4. using System.Text.Json;
  5. namespace Long.Core.Middleware;
  6. /// <summary>
  7. /// 异常捕获中间件
  8. /// </summary>
  9. public class LongExceptionCatch
  10. {
  11. /// <summary>
  12. /// 请求委托
  13. /// </summary>
  14. private readonly RequestDelegate _requestDelegate;
  15. public LongExceptionCatch(RequestDelegate requestDelegate)
  16. {
  17. _requestDelegate = requestDelegate;
  18. }
  19. /// <summary>
  20. /// 唤起
  21. /// </summary>
  22. /// <param name="httpContext"></param>
  23. /// <returns></returns>
  24. public async Task Invoke(HttpContext httpContext)
  25. {
  26. try
  27. {
  28. await _requestDelegate(httpContext);
  29. }
  30. catch (Exception ex)
  31. {
  32. httpContext.Response.StatusCode = 500;
  33. httpContext.Response.ContentType = "application/json;charset=utf-8";
  34. var result = new LongExceptionOutput()
  35. {
  36. Success = false,
  37. Message = "服务器内部错误:" + ex.Message,
  38. StatusCode = (int)HttpStatusCode.InternalServerError,
  39. Source = ex.Source ?? "",
  40. StackTrace = ex.StackTrace ?? "",
  41. TargetSite = ex.TargetSite,
  42. Data = ex.Data
  43. };
  44. await httpContext.Response.WriteAsync(JsonSerializer.Serialize(result));
  45. }
  46. }
  47. }