springboot 统一异常处理

基于@ControllerAdvice注解的Controller层的全局异常统一处理

定义错误信息enums

建立返回信息枚举enums来统一管理返回的信息

package com.main.enums;

import lombok.Getter;

@Getter
public enum ResultEnum {

    //基础
    UNKONW_ERROR(-1,"未知错误"),
    SUCCESE(0,"成功"),

    //College系列报错,系列号:1
    COLLEGE_NOT_EXIST(11,"不存在该系"),
    COLLEGE_NAME_ERROR(12,"系名不符合规定")
    ;

    private Integer code;

    private String msg;

    ResultEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

定义自己的异常

创建自己的Exception继承自RuntimeException

package com.main.exception;

import com.main.enums.ResultEnum;
import lombok.Data;

@Data
public class CollegeException extends RuntimeException{

    private Integer code;

    public CollegeException(ResultEnum resultEnum) {
        super(resultEnum.getMsg());
        this.code = resultEnum.getCode();
    }

}

抛出自定义异常

//Service层抛出异常
public CollegeDao findOne(String collegeId){
        CollegeDao collegeDao = repository.findById(collegeId).orElse(null);
        if (collegeDao == null){
            throw new CollegeException(ResultEnum.COLLEGE_NOT_EXIST);
        }
        return collegeDao;
    }
//抛出表单验证的异常
@PostMapping("/")
    public ResultVO save(@Validated CollegeForm collegeForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new CollegeException(ResultEnum.PARA_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultVOUtil.succese(collegeService.save(collegeForm));
    }

异常捕获

创建ExceptionHandle捕获Controller抛出的异常进行处理

  1. 捕获自定义异常
@ControllerAdvice
public class CollegeExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(CollegeExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(value = CollegeException.class)
    public ResultVO handler(CollegeException e){
        logger.info(e.getMessage());
        return ResultVOUtil.error(e.getCode(),e.getMessage());
    }

}
  1. 捕获其他未知的系统异常
@ControllerAdvice
public class UnknownExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(UnknownExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultVO handler(Exception e){
        logger.error(e.getMessage());
        return ResultVOUtil.error(ResultEnum.UNKONW_ERROR.getCode(),ResultEnum.UNKONW_ERROR.getMsg());
    }

}

完成统一异常处理,即使报错也能返回统一的数据格式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值