spring boot统一异常处理

  1. 创建通用返回值格式

详见:Spring Boot Web 自定义返回值(通用)

  1. 处理可预知运行时异常
@Data
public class RTException extends RuntimeException{
    // 步骤一定义的返回值类
    private Result result;
    
    public RTException(){}
    
    // 你可以将异常定义在ResultCode 枚举中,或者在return中自己添加
    public RTException(Result result){
        this.result = result;
    }
    
}

使用方式:

// 例如在ResultCode中定义数据库查找为空异常枚举 SQLDATANULL(false,-10,"数据库查找为空")
在逻辑中可以使用
    if(count == 0){
        throw new RTException(new Result(ResultCode.SQLDATANULL))
    }

// 或者直接传入错误信息,使用默认错误码
throw new RTException(new Result(ResultCode.FAIL,"错误信息"))
  1. @ControllerAdvice 注解定义全局异常处理类。此类中包含 @ExceptionHandler 注解的方法,负责处理所有 Controller 层抛出的 Exception 及其子类的异常。
@ControllerAdvice
public class GlobalExceptionHandler{
    
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handler(Exception e) {
            LOGGER.error("exception:{}", e.getMessage(), e);
            return new Result(ResultCode.FAIL,e.getMessage());
       
    }
}

使用:

@GetMapping(value = "/page")
    public Result selectSysUserPage( SysUserVO sysUserVO) throws Exception {
        return this.sysUserService.selectSysUserPage(sysUserVO);
    }
// 之前每个方法都要try-catch,逻辑基本一样。现在只需要继承BaseController,然后throws Exception即可。

写的匆忙,还是在Typora上写的,没有代码提示,哭唧唧。

不知道代码有没有问题,等我有时间跑一下,有好的方法欢迎留言交流!

posted @ 2020-04-01 21:58  Gyyyang  阅读(194)  评论(0编辑  收藏  举报