ExceptionMiddleware.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Net;
  3. using System.Security.Claims;
  4. using System.Threading.Tasks;
  5. using GxPress.Common.Exceptions;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.Extensions.Logging;
  8. using Newtonsoft.Json;
  9. namespace GxPress.Common.Middleware
  10. {
  11. /// <summary>
  12. /// 自定义异常中间件
  13. /// </summary>
  14. public class ExceptionMiddlewareDto
  15. {
  16. private readonly RequestDelegate _next;
  17. private readonly ILogger<ExceptionMiddlewareDto> _logger;
  18. private readonly IHttpContextAccessor _contextAccessor;
  19. //private readonly IUserService userService;
  20. public ExceptionMiddlewareDto(RequestDelegate next, ILogger<ExceptionMiddlewareDto> logger, IHttpContextAccessor contextAccessor)
  21. {
  22. _next = next;
  23. _logger = logger;
  24. _contextAccessor = contextAccessor;
  25. }
  26. public async Task Invoke(HttpContext context)
  27. {
  28. try
  29. {
  30. //
  31. await _next.Invoke(context);
  32. if (context.User != null)
  33. {
  34. var ty = _contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.Role);
  35. if (!ty.Value.Equals("Admin"))
  36. {
  37. }
  38. }
  39. }
  40. catch (BusinessException be)
  41. {
  42. _logger.LogDebug(be.Message);
  43. await HandleBusinessException(context, be);
  44. }
  45. catch (System.Exception ex)
  46. {
  47. _logger.LogError(ex, ex.Message);
  48. await HandleSystemException(context, ex);
  49. }
  50. }
  51. /// <summary>
  52. /// 处理业务异常
  53. /// </summary>
  54. /// <param name="context"></param>
  55. /// <param name="be"></param>
  56. /// <returns></returns>
  57. private Task HandleBusinessException(HttpContext context, BusinessException be)
  58. {
  59. context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
  60. context.Response.ContentType = "application/json;charset=utf-8";
  61. return context.Response.WriteAsync(JsonConvert.SerializeObject(new
  62. {
  63. be.Message,
  64. be.StackTrace
  65. }));
  66. }
  67. /// <summary>
  68. /// 处理系统异常
  69. /// </summary>
  70. /// <param name="context"></param>
  71. /// <param name="ex"></param>
  72. /// <returns></returns>
  73. private Task HandleSystemException(HttpContext context, Exception ex)
  74. {
  75. context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
  76. context.Response.ContentType = "application/json;charset=utf-8";
  77. return context.Response.WriteAsync(JsonConvert.SerializeObject(ex));
  78. }
  79. }
  80. }