ExceptionMiddleware.cs 2.9 KB

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