统一异常处理
使用SpringMVC后,异常就不必在三层代码去处理了,而是直接抛给框架,框架会将所有的异常统一转交给我们自定义的统一异常处理类来处理。
SpringMVC支持下面两个注解来实现全局异常处理
@RestControllerAdvice 标注在类上,声明当前类是一个用于专门处理异常的类
@ExceptionHandler 标注在方法上,声明当前方法可以处理哪些异常
1. 模拟异常
//模拟异常
//http://localhost:8080/user/demo21?type=1
@RequestMapping("/demo21")
public void demo21(Integer type) {
if (type == 1) { //ArithmeticException
int i = 1 / 0;
} else if (type == 2) { //NullPointerException
String s = null;
System.out.println(s.length());
} else { //ArrayIndexOutOfBoundsException
Integer[] arr = new Integer[2];
arr[5] = 1;
}
}
2. 全局异常处理
//通用异常处理器,只要程序中出现异常,都会来到这个类中进行处理
@RestControllerAdvice //@RestControllerAdvice 标注在类上,声明当前类是一个用于专门处理异常的类
public class CommonExceptionHandler {
//空指针异常
@ExceptionHandler(NullPointerException.class) //标注在方法上,声明当前方法可以处理那些异常
public String handlerNullPointerException(Exception e){
//1.打印日志(程序员排错)
e.printStackTrace();
//2.返回错误
return "NullPointerException";
}
//算术逻辑异常
@ExceptionHandler(ArithmeticException.class)
public String handlerArithmeticException(Exception e){
//1.打印日志(程序员排错)
e.printStackTrace();
//2.返回错误
return "ArithmeticException";
}
//数组角标越界异常
@ExceptionHandler(ArrayIndexOutOfBoundsException.class)
public String handlerArrayIndexOutOfBoundsException(Exception e){
//1.打印日志(程序员排错)
e.printStackTrace();
//2.返回错误
return "ArrayIndexOutOfBoundsException";
}
}