使用@ExceptionHandler 加@ControllerAdvice 注解
模拟异常发生
@RestController
@RequestMapping("/exception")
public class ExceptionController {
@RequestMapping("/show1")
public String showInfo1() {
String msg = null;
msg.length(); // NullPointerException
return "success";
}
@RequestMapping("/show2")
public String showInfo2() {
int a = 0;
int b = 100;
System.out.println(b / a); //ArithmeicExpetion
return "success";
}
}
全局异常处理类
@ControllerAdvice
public class GlobalException {
@ExceptionHandler(value = { NullPointerException.class })
public ModelAndView nullPointerExceptionHandler(Exception e) {
ModelAndView view = new ModelAndView();
view.setViewName("error");
view.addObject("error","空指针异常");
return view;
}
@ExceptionHandler(value = {ArithmeticException.class})
public ModelAndView arithmeticExceptionHandler(Exception e){
ModelAndView view = new ModelAndView();
view.setViewName("error");
view.addObject("error","算数运算异常");
return view;
}
}
跳转的页面(这里使用了thymeleaf)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>系统错误页面</h1>
<span th:text="${error}"></span>
</body>
</html>
测试结果:


本文展示了如何在Spring Boot中使用@ControllerAdvice和@ExceptionHandler进行全局异常处理,包括对NullPointerException和ArithmeticException的捕获,并将错误信息定向到一个统一的错误页面。通过这种方式,可以优雅地处理程序运行时可能遇到的异常,提供一致的用户体验。
4795

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



