Springboot项目全局异常统一处理

https://blog.csdn.net/hao_kkkkk/article/details/80538955?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param

  1. package com.youzan.cloud.ddyl.web;
  2. import com.youzan.cloud.ddyl.api.BizCodeConst;
  3. import com.youzan.cloud.ddyl.api.BizServiceException;
  4. import com.youzan.cloud.ddyl.web.support.UnauthorizedException;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.boot.web.servlet.error.ErrorController;
  7. import org.springframework.http.HttpStatus;
  8. import org.springframework.http.ResponseEntity;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.web.HttpRequestMethodNotSupportedException;
  11. import org.springframework.web.bind.MethodArgumentNotValidException;
  12. import org.springframework.web.bind.MissingServletRequestParameterException;
  13. import org.springframework.web.bind.annotation.ControllerAdvice;
  14. import org.springframework.web.bind.annotation.ExceptionHandler;
  15. import org.springframework.web.bind.annotation.RequestMapping;
  16. import org.springframework.web.bind.annotation.ResponseBody;
  17. import org.springframework.web.servlet.DispatcherServlet;
  18. import org.springframework.web.util.NestedServletException;
  19. import javax.servlet.http.HttpServletRequest;
  20. import java.util.Objects;
  21. import java.util.Optional;
  22. import java.util.function.Supplier;
  23. /**
  24. * @author bomee shiaupo@qq.com
  25. * @since 2020/9/5
  26. */
  27. @Controller
  28. @ControllerAdvice
  29. @RequestMapping({"${server.error.path:${error.path:/error}}"})
  30. public class JsonResultErrorController implements ErrorController {
  31. @Value("${server.error.path:${error.path:/error}}")
  32. private String errorPath;
  33. @RequestMapping
  34. public ResponseEntity<JsonResult<?>> error(HttpServletRequest request) {
  35. Throwable error = getError(request);
  36. HttpStatus status = getStatus(request);
  37. return new ResponseEntity<>(
  38. new JsonResult<>(status.value(), "服务器当前不能处理该请求", ((Supplier<String>) () -> {
  39. Throwable ex = error;
  40. while (ex != null) {
  41. if (!Objects.isNull(ex.getMessage())) {
  42. return ex.getMessage();
  43. }
  44. ex = ex.getCause();
  45. }
  46. return null;
  47. }).get()), status);
  48. }
  49. @ExceptionHandler(UnauthorizedException.class)
  50. @ResponseBody
  51. public ResponseEntity<JsonResult<?>> handleException(UnauthorizedException exception) {
  52. return new ResponseEntity<>(
  53. new JsonResult<>(HttpStatus.UNAUTHORIZED.value(), exception.getMessage(), null),
  54. HttpStatus.UNAUTHORIZED);
  55. }
  56. @ExceptionHandler(BizServiceException.class)
  57. @ResponseBody
  58. public ResponseEntity<JsonResult<?>> handleException(BizServiceException exception) {
  59. return new ResponseEntity<>(
  60. new JsonResult<>(exception.getCode() == null ? BizCodeConst.BIZ_UNDEFINED_EX : exception.getCode(), exception.getMessage(), null),
  61. HttpStatus.BAD_REQUEST);
  62. }
  63. @ExceptionHandler(MethodArgumentNotValidException.class)
  64. @ResponseBody
  65. public ResponseEntity<JsonResult<?>> handleException(MethodArgumentNotValidException exception) {
  66. return new ResponseEntity<>(
  67. new JsonResult<>(HttpStatus.BAD_REQUEST.value(), exception.getBindingResult().getAllErrors().get(0).getDefaultMessage(), null),
  68. HttpStatus.BAD_REQUEST);
  69. }
  70. @ExceptionHandler(MissingServletRequestParameterException.class)
  71. @ResponseBody
  72. public ResponseEntity<JsonResult<?>> handleException(MissingServletRequestParameterException exception) {
  73. return new ResponseEntity<>(
  74. new JsonResult<>(HttpStatus.BAD_REQUEST.value(), "缺失请求参数" + exception.getParameterName(), null),
  75. HttpStatus.BAD_REQUEST);
  76. }
  77. @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
  78. @ResponseBody
  79. public ResponseEntity<JsonResult<?>> handleException(HttpRequestMethodNotSupportedException exception) {
  80. return new ResponseEntity<>(
  81. new JsonResult<>(HttpStatus.METHOD_NOT_ALLOWED.value(), exception.getMethod() + "不被支持", null),
  82. HttpStatus.METHOD_NOT_ALLOWED);
  83. }
  84. protected HttpStatus getStatus(HttpServletRequest request) {
  85. Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
  86. if (statusCode == null) {
  87. return HttpStatus.INTERNAL_SERVER_ERROR;
  88. } else {
  89. try {
  90. return HttpStatus.valueOf(statusCode);
  91. } catch (Exception e) {
  92. return HttpStatus.INTERNAL_SERVER_ERROR;
  93. }
  94. }
  95. }
  96. protected Throwable getError(HttpServletRequest request) {
  97. Throwable throwable =
  98. (Throwable) Optional.ofNullable(request.getAttribute("javax.servlet.error.exception"))
  99. .orElseGet(() -> request.getAttribute(DispatcherServlet.EXCEPTION_ATTRIBUTE));
  100. if (throwable instanceof NestedServletException) {
  101. return throwable.getCause();
  102. }
  103. return throwable;
  104. }
  105. @Override
  106. public String getErrorPath() {
  107. return errorPath;
  108. }
  109. }
package com.youzan.cloud.ddyl.api;

/**
 * 业务异常基类
 *
 * @author bomee shiaupo@qq.com
 * @since 2020/9/13
 */
public class BizServiceException extends RuntimeException {
    private final Integer code;

    public BizServiceException(String message, Throwable e) {
        this(null, message, e);
    }

    public BizServiceException(Integer code, String message) {
        this(code, message, null);
    }

    public BizServiceException(Integer code, String message, Throwable e) {
        super(message, e);
        this.code = code;
    }

    /**
     * 尽可能为每个业务异常划分一个Code
     *
     * @return Code
     */
    public Integer getCode() {
        return code;
    }
}
package com.youzan.cloud.ddyl.api.exception;

import com.youzan.cloud.ddyl.api.BizCodeConst;
import com.youzan.cloud.ddyl.api.BizServiceException;

/**
 * @author bomee shiaupo@qq.com
 * @since 2020/9/19
 */
public class ActivityTimeConflictException extends BizServiceException {
    public ActivityTimeConflictException(String message) {
        super(BizCodeConst.ACT_TIME_CONFLICT, message, null);
    }
}

重试

https://toutiao.io/posts/rhskkte/preview

https://yq.aliyun.com/articles/609440

https://juejin.im/post/6844904102468517895

https://blog.csdn.net/u011116672/article/details/77823867

https://juejin.im/post/6844904102468517895

http://zengkairou.com/2019/02/01/spring-retry/