ExceptionHandlingMiddleware.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. default:
  68. response.StatusCode = StatusCodes.Status500InternalServerError;
  69. errorResponse.Msg = exception.Message;
  70. break;
  71. }
  72. _logger.LogError(exception.Message);
  73. var result = JsonConvert.SerializeObject(errorResponse);
  74. await context.Response.WriteAsync(result);
  75. }
  76. }
  77. }