GlobalExceptionHandler.java 5.5 KB

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