ExceptionHandlingMiddleware.cs 5.1 KB

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