GlobalExceptionHandler.java 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. package com.cyksj.web;
  2. import cn.dev33.satoken.exception.NotLoginException;
  3. import cn.dev33.satoken.exception.NotPermissionException;
  4. import cn.dev33.satoken.exception.NotRoleException;
  5. import cn.hutool.core.lang.Validator;
  6. import com.cyksj.common.exception.BusinessRuntimeException;
  7. import com.cyksj.dto.Result;
  8. import com.cyksj.enums.GatewayApiCode;
  9. import com.cyksj.enums.GatewayResponse;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.validation.BindException;
  13. import org.springframework.validation.FieldError;
  14. import org.springframework.web.bind.annotation.ExceptionHandler;
  15. import org.springframework.web.bind.annotation.RestControllerAdvice;
  16. import javax.servlet.http.HttpServletRequest;
  17. import javax.validation.ConstraintViolation;
  18. import javax.validation.ConstraintViolationException;
  19. import java.util.List;
  20. import java.util.Set;
  21. import java.util.TreeSet;
  22. /**
  23. * @description 异常全局拦截
  24. * @author chan
  25. * @date 2021-03-22 9:51 下午
  26. */
  27. @Slf4j
  28. @RestControllerAdvice
  29. public class GlobalExceptionHandler {
  30. @Autowired
  31. protected HttpServletRequest request;
  32. private final static List<String> token = List.of("token无效", "token已过期");
  33. @ExceptionHandler(value = {Exception.class})
  34. public Result<String> handleNoteException(Exception e) {
  35. String requestId = java.util.UUID.randomUUID().toString();
  36. log.error("Request failed requestId={} path={}", requestId, request.getRequestURI(), e);
  37. String message = e instanceof BusinessRuntimeException ? e.getMessage() : "系统异常,请稍后重试";
  38. GatewayApiCode apiCode = null;
  39. if (e instanceof BusinessRuntimeException) {
  40. BusinessRuntimeException ee = (BusinessRuntimeException) e;
  41. String code = ee.getCode();
  42. if (Validator.isNumber(code)) {
  43. if (GatewayApiCode.CMS_TOKEN_VALID.getCode().equals(Integer.parseInt(code))) {
  44. apiCode = GatewayApiCode.CMS_TOKEN_VALID;
  45. }
  46. }
  47. }
  48. if (e instanceof NotLoginException) {
  49. //未登录
  50. NotLoginException ee = (NotLoginException) e;
  51. if (token.contains(ee.getMessage())) {
  52. apiCode = GatewayApiCode.CMS_TOKEN_VALID;
  53. } else if ("token已被踢下线".equals(ee.getMessage())) {
  54. apiCode = GatewayApiCode.CMS_TOKEN_OUT_LINE;
  55. } else {
  56. apiCode = GatewayApiCode.CMS_USER_NO_LOGIN;
  57. }
  58. } else if (e instanceof NotRoleException) {
  59. // 如果是角色异常
  60. NotRoleException ee = (NotRoleException) e;
  61. apiCode = GatewayApiCode.CMS_USER_NO_ROLE;
  62. } else if (e instanceof NotPermissionException) {
  63. // 如果是权限异常
  64. NotPermissionException ee = (NotPermissionException) e;
  65. apiCode = GatewayApiCode.CMS_USER_NO_PERMISSION;
  66. }
  67. if (apiCode != null) {
  68. return GatewayResponse.FAIL.newBuilder().buildGatewayCode(apiCode).toResult();
  69. }
  70. return GatewayResponse.FAIL.newBuilder().setMsg(message).toResult("requestId=" + requestId);
  71. }
  72. @ExceptionHandler(value = ConstraintViolationException.class)
  73. public Result<String> ConstraintViolationException(ConstraintViolationException ex) {
  74. String message = "";
  75. // 使用TreeSet是为了让输出的内容有序输出(默认验证的顺序是随机的)
  76. Set<String> errorInfoSet = new TreeSet<String>();
  77. Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
  78. if (!violations.isEmpty()) {
  79. for (ConstraintViolation<?> item : violations) {
  80. System.out.println(item.getPropertyPath());
  81. // 遍历错误字段信息
  82. errorInfoSet.add(item.getMessage());
  83. }
  84. StringBuilder sbf = new StringBuilder();
  85. for (String errorInfo : errorInfoSet) {
  86. sbf.append(errorInfo);
  87. sbf.append(",");
  88. }
  89. message = sbf.substring(0, sbf.length() - 1);
  90. }
  91. log.error("错误字段 信息: \n Value: {}", message);
  92. return GatewayResponse.FAIL.newBuilder().buildGatewayCode(GatewayApiCode.PARAMETER_MISSING_ERROR).setMsg(message).toResult();
  93. }
  94. @ExceptionHandler(BindException.class)
  95. public Result<String> BindException(BindException bindingResult) {
  96. // 验证参数信息是否有效
  97. if (bindingResult.hasErrors()) {
  98. // 获取错误字段信息集合
  99. List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
  100. // 使用TreeSet是为了让输出的内容有序输出(默认验证的顺序是随机的)
  101. Set<String> errorInfoSet = new TreeSet<String>();
  102. for (FieldError fieldError : fieldErrorList) {
  103. // 遍历错误字段信息
  104. errorInfoSet.add(fieldError.getDefaultMessage());
  105. }
  106. StringBuilder sbf = new StringBuilder();
  107. for (String errorInfo : errorInfoSet) {
  108. sbf.append(errorInfo);
  109. sbf.append(",");
  110. }
  111. String message = sbf.substring(0, sbf.length() - 1);
  112. log.error("验证参数信息是否有效 错误信息: \n Value: {}", message);
  113. return GatewayResponse.FAIL.newBuilder().buildGatewayCode(GatewayApiCode.PARAMETER_MISSING_ERROR).setMsg(message).toResult();
  114. }
  115. return GatewayResponse.SUCCESS.newBuilder().buildGatewayCode(GatewayApiCode.SUCCESS).setMsg("参数校验通过").toResult();
  116. }
  117. }