ExceptionHandlingMiddleware.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. namespace OASystem.API.Middlewares
  2. {
  3. /// <summary>
  4. /// 全局异常捕获中间件
  5. /// </summary>
  6. public class ExceptionHandlingMiddleware
  7. {
  8. private readonly RequestDelegate _next; // 用来处理上下文请求
  9. private readonly ILogger<ExceptionHandlingMiddleware> _logger;
  10. /// <summary>
  11. /// 初始化
  12. /// </summary>
  13. /// <param name="next"></param>
  14. /// <param name="logger"></param>
  15. public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
  16. {
  17. _next = next;
  18. _logger = logger;
  19. }
  20. /// <summary>
  21. /// 执行中间件
  22. /// </summary>
  23. /// <param name="httpContext"></param>
  24. /// <returns></returns>
  25. public async Task InvokeAsync(HttpContext httpContext)
  26. {
  27. try
  28. {
  29. await _next(httpContext); //要么在中间件中处理,要么被传递到下一个中间件中去
  30. }
  31. catch (Exception ex)
  32. {
  33. await HandleExceptionAsync(httpContext, ex); // 捕获异常了 在HandleExceptionAsync中处理
  34. }
  35. }
  36. /// <summary>
  37. /// 异步处理异常
  38. /// </summary>
  39. /// <param name="context"></param>
  40. /// <param name="exception"></param>
  41. /// <returns></returns>
  42. private async Task HandleExceptionAsync(HttpContext context, Exception exception)
  43. {
  44. context.Response.ContentType = "application/json"; // 返回json 类型
  45. var response = context.Response;
  46. var errorResponse = new JsonView
  47. {
  48. Code = StatusCodes.Status500InternalServerError,
  49. Data = ""
  50. }; // 自定义的异常错误信息类型
  51. switch (exception)
  52. {
  53. case ApplicationException ex:
  54. if (ex.Message.Contains("Invalid token"))
  55. {
  56. response.StatusCode = StatusCodes.Status403Forbidden;
  57. errorResponse.Msg = ex.Message;
  58. break;
  59. }
  60. response.StatusCode = StatusCodes.Status400BadRequest;
  61. errorResponse.Msg = ex.Message;
  62. break;
  63. case KeyNotFoundException ex:
  64. response.StatusCode = StatusCodes.Status404NotFound;
  65. errorResponse.Msg = ex.Message;
  66. break;
  67. case SqlSugarException ex:
  68. response.StatusCode = StatusCodes.Status204NoContent;
  69. if (ex.Message.Contains("timeout")) errorResponse.Msg = $"数据库连接超时,请稍后重试。";
  70. else errorResponse.Msg = ex.Message;
  71. break;
  72. default:
  73. response.StatusCode = StatusCodes.Status500InternalServerError;
  74. errorResponse.Msg = exception.Message;
  75. break;
  76. }
  77. _logger.LogError(exception.Message);
  78. var result = JsonConvert.SerializeObject(errorResponse);
  79. await context.Response.WriteAsync(result);
  80. }
  81. }
  82. }