GlobalExceptionHandler.java 6.0 KB

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