第十八节:学习统一异常处理(自学Spring boot 3.x的第五天)

这节记录下如何通过AOP方式统一处理异常拦截。

第一步:

新建一个exception包,创建一个ExcetionHandler.java(名字随意取)

package cn.wcyf.wcai.exception;

import cn.wcyf.wcai.common.Result;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ExceptionHandler {
    // 处理运行时异常
    @org.springframework.web.bind.annotation.ExceptionHandler(BussinessException.class)
    public Result handlerException(BussinessException e){
        //处理逻辑
        return Result.fail(e.getMessage());
    }
    @org.springframework.web.bind.annotation.ExceptionHandler(ArithmeticException.class)
    public Result handlerArithmeticException(ArithmeticException e){
        return Result.fail(e.getMessage());
    }
}

要处理哪个异常,就在注解后面加上该拦截类的class。

第二步:测试

写一个错误,使得访问时报错。

    @GetMapping("/{id}")
    public Result<Student> getById(@PathVariable Integer id){
        int o = 1/0 ;
        if(id==10||id==11){
            return Result.success(studentService.getById(id));
//            return ReturnResult.createSuccessfulResp(ResultEnum.SUCCESS.getDesc(),studentService.getById(id));
        }else {
            return Result.fail(ResultEnum.ILLEGAL_ARGUMENT);
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mero技术博客

创作不易,打赏小弟可否

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值