ExceptionHandlingMiddleware.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. 
  2. using Microsoft.Data.SqlClient;
  3. namespace OASystem.API.Middlewares
  4. {
  5. /// <summary>
  6. /// 全局异常捕获中间件
  7. /// </summary>
  8. public class ExceptionHandlingMiddleware
  9. {
  10. private readonly RequestDelegate _next; // 用来处理上下文请求
  11. private readonly ILogger<ExceptionHandlingMiddleware> _logger;
  12. /// <summary>
  13. /// 初始化
  14. /// </summary>
  15. /// <param name="next"></param>
  16. /// <param name="logger"></param>
  17. public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
  18. {
  19. _next = next;
  20. _logger = logger;
  21. }
  22. /// <summary>
  23. /// 执行中间件
  24. /// </summary>
  25. /// <param name="httpContext"></param>
  26. /// <param name="db"></param>
  27. /// <returns></returns>
  28. public async Task InvokeAsync(HttpContext httpContext, SqlSugarClient db)
  29. {
  30. try
  31. {
  32. await _next(httpContext); //要么在中间件中处理,要么被传递到下一个中间件中去
  33. }
  34. catch (Exception ex)
  35. {
  36. await HandleExceptionAsync(httpContext, ex, db); // 捕获异常了 在HandleExceptionAsync中处理
  37. }
  38. }
  39. /// <summary>
  40. /// 自定义全局异常处理方法
  41. /// </summary>
  42. /// <param name="context"></param>
  43. /// <param name="exception"></param>
  44. /// <param name="db"></param>
  45. /// <returns></returns>
  46. private async Task HandleExceptionAsync(HttpContext context, Exception exception, SqlSugarClient db)
  47. {
  48. //if (db.Ado != null && db.Ado.Transaction != null)
  49. //{
  50. // try
  51. // {
  52. // db.Ado.RollbackTran();
  53. // }
  54. // catch (Exception ex)
  55. // {
  56. // _logger.LogError("Error rolling back transaction: {ErrorMessage}", ex.Message);
  57. // }
  58. //}
  59. // 检查响应是否已开始
  60. if (!context.Response.HasStarted)
  61. {
  62. context.Response.ContentType = "application/json"; // 设置响应内容类型为 JSON
  63. var response = context.Response;
  64. var errorResponse = new JsonView
  65. {
  66. Code = StatusCodes.Status500InternalServerError,
  67. Data = ""
  68. };
  69. // 根据异常类型设置不同的响应状态码和消息
  70. switch (exception)
  71. {
  72. case SqlException sqlEx when sqlEx.Number == -2:
  73. response.StatusCode = StatusCodes.Status503ServiceUnavailable;
  74. errorResponse.Msg = "数据库连接超时,请稍后重试。";
  75. break;
  76. case SqlException sqlEx when sqlEx.Number == -4:
  77. response.StatusCode = StatusCodes.Status503ServiceUnavailable;
  78. errorResponse.Msg = "数据库连接池耗尽,请稍后重试。";
  79. break;
  80. case ApplicationException ex when ex.Message.Contains("Invalid token"):
  81. response.StatusCode = StatusCodes.Status403Forbidden;
  82. errorResponse.Msg = ex.Message;
  83. break;
  84. case ApplicationException ex:
  85. response.StatusCode = StatusCodes.Status400BadRequest;
  86. errorResponse.Msg = ex.Message;
  87. break;
  88. case KeyNotFoundException ex:
  89. response.StatusCode = StatusCodes.Status404NotFound;
  90. errorResponse.Msg = ex.Message;
  91. break;
  92. case SqlSugarException ex:
  93. response.StatusCode = ex.Message.Contains("timeout")
  94. ? StatusCodes.Status503ServiceUnavailable
  95. : StatusCodes.Status500InternalServerError;
  96. errorResponse.Msg = ex.Message.Contains("timeout")
  97. ? "数据库连接超时,请稍后重试。"
  98. : ex.Message;
  99. break;
  100. default:
  101. response.StatusCode = StatusCodes.Status500InternalServerError;
  102. errorResponse.Msg = "服务器内部错误"; // 不直接暴露异常详细信息
  103. break;
  104. }
  105. _logger.LogError(exception, "An exception occurred."); // 记录异常详细信息
  106. var result = JsonConvert.SerializeObject(errorResponse);
  107. await context.Response.WriteAsync(result); // 将错误响应写入客户端
  108. }
  109. else
  110. {
  111. // 如果响应已开始,记录日志但不做进一步处理
  112. _logger.LogError(exception, "An exception occurred after response started.");
  113. }
  114. }
  115. }
  116. }