一、背景
1.在Spring Boot项目中,代码出现异常会跳转到/error页面进行错误展示,对用户和前端都不友好,我们希望以友好的方式来显示异常。
二、异常演示
1.先来演示一下默认的异常处理
@RestController
public class IndexController {
@RequestMapping("/getResult")
public int getResult(){
return 10 / 0;
}
@RequestMapping("/getResult1")
public int getResult1(){
int[] arr = new int[1];
arr[1] = 2;
return 2;
}
@PostMapping("/param")
public String param(Model model){
return (String) model.asMap().get("param");
}
}
2.发生异常页面显示(已经处理好的)
三、全局异常处理器
1.下面我们就上面的问题来进行解决,首先我们配置一个全局异常处理器
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* ExceptionHandler 的属性为异常的class对象, 如果不指定就是方法参数的class, 且同一个异常不能重复出现多个方法中
* 此处使用ResponseBody返回json数据,也可以和Controller方法一样返回其他类型
*/
@ResponseBody
@ExceptionHandler
public Result handlerException(Exception e) {
return new Result(1000, e.getMessage());
}
/**
* 一个方法可以处理多个异常, 指定多个异常的class, 但是方法参数只能是一个,即多个异常的父类
*/
@ResponseBody
@ExceptionHandler({ArrayIndexOutOfBoundsException.class})
public Result handlerMathException(Exception e) {
return new Result(2000, e.getMessage());
}
}
2.Result
public class Result implements Serializable {
private static final long serialVersionUID = -429942488081558386L;
private int code;
private String message;
public Result(int code, String message) {
this.code = code;
this.message = message;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
3.分析
handlerException方法能接受的的参数很多,按需填入即可
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
/**
* Exceptions handled by the annotated method. If empty, will default to any
* exceptions listed in the method argument list.
*/
Class<? extends Throwable>[] value() default {};
}
ExceptionHandler注解的值是一个列表,应该你可以传入多种不同的Exception。你也可以指定好几个异常处理器来处理不同的异常,如下所示。
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* ExceptionHandler 的属性为异常的class对象, 如果不指定就是方法参数的class, 且同一个异常不能重复出现多个方法中
* 此处使用ResponseBody返回json数据,也可以和Controller方法一样返回其他类型
*/
@ResponseBody
@ExceptionHandler
public Result handlerException(Exception e) {
return new Result(1000, e.getMessage());
}
/**
* 一个方法可以处理多个异常, 指定多个异常的class, 但是方法参数只能是一个,即多个异常的父类
*/
@ResponseBody
@ExceptionHandler({ArithmeticException.class, ArrayIndexOutOfBoundsException.class})
public Result handlerMathException(Exception e) {
return new Result(2000, e.getMessage());
}
}
四、结束
上面就是简简单单的对异常的处理!!!