Spring Boot 自定义异常及统一异常处理

自定义异常

自定义异常要继承RuntimeException

public class ShowtimeException extends RuntimeException {

    private Integer code;

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

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}

异常处理类
用@ControllerAdvice申明的类可以在Spring扫描时自动扫描,在异常的处理中@ControllerAdvice会优先选择用@ExceptionHandler标注的方法来做异常的处理。

@ControllerAdvice
public class ExceptionHandle {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e){
        // 判断异常是自定义异常
        if (e instanceof ShowtimeException){
            ShowtimeException showtimeException = (ShowtimeException) e;
            return ResultUtil.fail(showtimeException.getCode(), showtimeException.getMessage());
        } else {

            return ResultUtil.fail(-1, "e.getMessage()");
        }

    }
}

这样当我们在代码中抛出自定义异常时,就可以被捕获,返回统一格式的结果
Controller中的代码为:

@GetMapping("/showtime/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception {
        showtimeService.getAge(id);

    }

Service中的代码为:

@Service
public class ShowtimeService {

    @Autowired
    private ShowtimeRepository showtimeRepository;

    public void getAge(Integer id) throws Exception {
        Showtime showtime = showtimeRepository.getOne(id);
        Integer age = showtime.getAge();
        if (age < 10){
            throw new ShowtimeException(ResultEnum.ERROR_ONE);
        } if (age > 12 && age < 18){
            throw new ShowtimeException(ResultEnum.ERROR_TWO);
        }
    }
}

通过postman发送请求,http://localhost:9080/showtime/getAge/2 ,返回结果:

{
    "msg": "年龄大于12小于18",
    "code": 1,
    "data": null
}

参考慕课网地址: Aop之统一异常处理 http://www.imooc.com/learn/810

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值