ExceptionHandlingMiddleware.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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 BusinessException businessEx: // 新增:处理 BusinessException
  73. response.StatusCode = StatusCodes.Status400BadRequest;
  74. errorResponse.Msg = businessEx.Message;
  75. errorResponse.Code = StatusCodes.Status400BadRequest; // 设置正确的 HTTP 状态码
  76. break;
  77. case SqlException sqlEx when sqlEx.Number == -2:
  78. response.StatusCode = StatusCodes.Status503ServiceUnavailable;
  79. errorResponse.Msg = "数据库连接超时,请稍后重试。";
  80. break;
  81. case SqlException sqlEx when sqlEx.Number == -4:
  82. response.StatusCode = StatusCodes.Status503ServiceUnavailable;
  83. errorResponse.Msg = "数据库连接池耗尽,请稍后重试。";
  84. break;
  85. case ApplicationException ex when ex.Message.Contains("Invalid token"):
  86. response.StatusCode = StatusCodes.Status403Forbidden;
  87. errorResponse.Msg = ex.Message;
  88. break;
  89. case ApplicationException ex:
  90. response.StatusCode = StatusCodes.Status400BadRequest;
  91. errorResponse.Msg = ex.Message;
  92. break;
  93. case KeyNotFoundException ex:
  94. response.StatusCode = StatusCodes.Status404NotFound;
  95. errorResponse.Msg = ex.Message;
  96. break;
  97. case SqlSugarException ex:
  98. response.StatusCode = ex.Message.Contains("timeout")
  99. ? StatusCodes.Status503ServiceUnavailable
  100. : StatusCodes.Status500InternalServerError;
  101. errorResponse.Msg = ex.Message.Contains("timeout")
  102. ? "数据库连接超时,请稍后重试。"
  103. : ex.Message;
  104. break;
  105. default:
  106. response.StatusCode = StatusCodes.Status500InternalServerError;
  107. errorResponse.Msg = "服务器内部错误"; // 不直接暴露异常详细信息
  108. break;
  109. }
  110. _logger.LogError(exception, "An exception occurred."); // 记录异常详细信息
  111. var result = JsonConvert.SerializeObject(errorResponse);
  112. await context.Response.WriteAsync(result); // 将错误响应写入客户端
  113. }
  114. else
  115. {
  116. // 如果响应已开始,记录日志但不做进一步处理
  117. _logger.LogError(exception, "An exception occurred after response started.");
  118. }
  119. }
  120. }
  121. }