ControllerAdvice
# 统一异常处理
# @ControllerAdvice
创建类加上@ControllerAdvice注解,定义异常处理方法(使用@ExceptionHandler标识可以处理的异常);
在类上加上@Component注解,注入容器;
@ControllerAdvice
@Component
public class MyControllerAdvice {
@ExceptionHandler({NullPointerException.class,ArithmeticException.class})
public ModelAndView handlerException(Exception ex){
//如果出现了相关的异常,就会调用该方法
String msg = ex.getMessage();
ModelAndView modelAndView = new ModelAndView();
//把异常信息存入域中
modelAndView.addObject("msg",msg);
//跳转到error.jsp
modelAndView.setViewName("/WEB-INF/page/error.jsp");
return modelAndView;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16