这里使用@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;
}
}
本文介绍如何在SpringBoot应用中使用@ControllerAdvice注解创建全局异常处理器,包括创建类、处理异常的方法实现,以及注意控制器外异常处理的局限性。实例演示了如何捕获并返回Controller层的RuntimeException。
1511

被折叠的 条评论
为什么被折叠?



