SpringBoot异常统一处理

这里使用@ControllerAdvice,在类上使用这个注解后,表示为全局异常处理类

步骤:

  • 创建异常处理类添加注解@ControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler {
}
  • 在类中实现具体的处理流程
@ControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(RuntimeException.class)
    public String handlerException(Exception e) {
        String msg = e.getMessage();
        return "异常信息:" + msg;
    }
    
}
  • 测试异常
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findUser.do")
    public User findUser(Integer id) {
        if (id > 10) {
            throw new RuntimeException("controller错误");
        }
        User user = userService.findUser(id);
        return user;
    }

}

使用postman进行测试:

 

注意:在SpringBoot中的

   基于@ControllerAdvice注解的全局异常统一处理只能针对于Controller层的异常,意思是只能捕获到Controller层的异常,在service层或者其他层面的异常都不能捕获。

我之前在业务逻辑层中抛出了异常,一直没有被捕获到,找了部分博客,错误代码:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @DefineMyAop  // 自定义注解,添加aop
    public User findUser(Integer id) {
        if (id > 10) {
            throw new RuntimeException("参数异常");
        }
        User user = userMapper.findUser(id);
        System.out.println(user);
        return user;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值