Java SpringBoot

前言

开发SpringBoot项目过程中,不可避免的需要处理各种异常,SpringMVC架构中各层会出现大量的try {...} catch {...} finally {...}代码块,不仅有大量的冗余代码,而且还影响代码的可读性。这样就需要定义个全局统一异常处理器,以便业务层再也不必处理异常。

推荐理由

  • 代码复制到项目中通过简单的配置即可实现
  • 可以灵活的根据自己的业务异常进行更细粒度的扩展

    实践

    1、封装统一返回结果类

    SpringBoot项目中统一异常处理实现 - 图1
    源代码 ```java public class AjaxResult {
    //是否成功
    private Boolean success;
    //状态码
    private Integer code;
    //提示信息
    private String msg;
    //数据
    private Object data;
    public AjaxResult() {

    }
    //自定义返回结果的构造方法
    public AjaxResult(Boolean success,Integer code, String msg,Object data) {

    1. this.success = success;
    2. this.code = code;
    3. this.msg = msg;
    4. this.data = data;

    }
    //自定义异常返回的结果
    public static AjaxResult defineError(BusinessException de){

    1. AjaxResult result = new AjaxResult();
    2. result.setSuccess(false);
    3. result.setCode(de.getErrorCode());
    4. result.setMsg(de.getErrorMsg());
    5. result.setData(null);
    6. return result;

    }
    //其他异常处理方法返回的结果
    public static AjaxResult otherError(ErrorEnum errorEnum){

    1. AjaxResult result = new AjaxResult();
    2. result.setMsg(errorEnum.getErrorMsg());
    3. result.setCode(errorEnum.getErrorCode());
    4. result.setSuccess(false);
    5. result.setData(null);
    6. return result;

    }
    public Boolean getSuccess() {

    1. return success;

    }
    public void setSuccess(Boolean success) {

    1. this.success = success;

    }
    public Integer getCode() {

    1. return code;

    }
    public void setCode(Integer code) {

    1. this.code = code;

    }
    public String getMsg() {

    1. return msg;

    }
    public void setMsg(String msg) {

    1. this.msg = msg;

    }
    public Object getData() {

    1. return data;

    }
    public void setData(Object data) {

    1. this.data = data;

    }

}

  1. <a name="HUvdB"></a>
  2. ### 2、自定义异常封装类
  3. ![](https://cdn.nlark.com/yuque/0/2022/png/396745/1650115962959-54d936a4-bdc8-482c-9693-839ec97018ed.png#clientId=u1aaedbf3-9077-4&crop=0&crop=0&crop=1&crop=1&from=paste&id=uaaa07f98&margin=%5Bobject%20Object%5D&originHeight=655&originWidth=1080&originalType=url&ratio=1&rotation=0&showTitle=false&status=done&style=shadow&taskId=u57195f5a-4012-4dc0-a534-5e1d5fb7ddc&title=)<br />源码:
  4. ```java
  5. public class BusinessException extends RuntimeException {
  6. private static final long serialVersionUID = 1L;
  7. /**
  8. * 错误状态码
  9. */
  10. protected Integer errorCode;
  11. /**
  12. * 错误提示
  13. */
  14. protected String errorMsg;
  15. public BusinessException(){
  16. }
  17. public BusinessException(Integer errorCode, String errorMsg) {
  18. this.errorCode = errorCode;
  19. this.errorMsg = errorMsg;
  20. }
  21. public Integer getErrorCode() {
  22. return errorCode;
  23. }
  24. public void setErrorCode(Integer errorCode) {
  25. this.errorCode = errorCode;
  26. }
  27. public String getErrorMsg() {
  28. return errorMsg;
  29. }
  30. public void setErrorMsg(String errorMsg) {
  31. this.errorMsg = errorMsg;
  32. }
  33. }

3、错误枚举,拒绝硬编码

SpringBoot项目中统一异常处理实现 - 图2
源码

  1. public enum ErrorEnum {
  2. // 数据操作错误定义
  3. SUCCESS(200, "成功"),
  4. NO_PERMISSION(403,"无权限"),
  5. NO_AUTH(401,"未登录"),
  6. NOT_FOUND(404, "未找到该资源!"),
  7. INTERNAL_SERVER_ERROR(500, "服务器异常请联系管理员"),
  8. ;
  9. /** 错误码 */
  10. private Integer errorCode;
  11. /** 错误信息 */
  12. private String errorMsg;
  13. ErrorEnum(Integer errorCode, String errorMsg) {
  14. this.errorCode = errorCode;
  15. this.errorMsg = errorMsg;
  16. }
  17. public Integer getErrorCode() {
  18. return errorCode;
  19. }
  20. public String getErrorMsg() {
  21. return errorMsg;
  22. }
  23. }

4、全局异常处理类

SpringBoot项目中统一异常处理实现 - 图3
源码

  1. /**
  2. * 全局异常处理器
  3. *
  4. */
  5. @RestControllerAdvice
  6. public class GlobalExceptionHandler {
  7. private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
  8. /**
  9. * 处理自定义异常
  10. *
  11. */
  12. @ExceptionHandler(value = BusinessException.class)
  13. public AjaxResult bizExceptionHandler(BusinessException e) {
  14. log.error(e.getMessage(), e);
  15. return AjaxResult.defineError(e);
  16. }
  17. /**
  18. *处理其他异常
  19. *
  20. */
  21. @ExceptionHandler(value = Exception.class)
  22. public AjaxResult exceptionHandler( Exception e) {
  23. log.error(e.getMessage(), e);
  24. return AjaxResult.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);
  25. }
  26. }

5、测试

SpringBoot项目中统一异常处理实现 - 图4