一、什么是统一异常处理

1、制造异常

除以0

1
int a = 10/0;

img

2、什么是统一异常处理

我们想让异常结果也显示为统一的返回结果对象,并且统一处理系统的异常信息,那么需要统一异常处理

二、统一异常处理

1、创建统一异常处理器

在service-base中创建统一异常处理类GlobalExceptionHandler.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 统一异常处理类
*/

@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public R error(Exception e){
e.printStackTrace();
return R.error();
}
}

2、测试

返回统一错误结果

img

三、处理特定异常

1、添加异常处理方法

GlobalExceptionHandler.java中添加

1
2
3
4
5
6
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public R error(ArithmeticException e){
e.printStackTrace();
return R.error().message("执行了自定义异常");
}

2、测试

img

四、自定义异常

1、创建自定义异常类

1
2
3
4
5
6
7
8
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GuliException extends RuntimeException {
@ApiModelProperty(value = "状态码")
private Integer code;
private String msg;
}

2、业务中需要的位置抛出GuliException

1
2
3
4
5
try {
int a = 10/0;
}catch(Exception e) {
throw new GuliException(20001,"出现自定义异常");
}

3、添加异常处理方法

GlobalExceptionHandler.java中添加

1
2
3
4
5
6
@ExceptionHandler(GuliException.class)
@ResponseBody
public R error(GuliException e){
e.printStackTrace();
return R.error().message(e.getMsg()).code(e.getCode());
}

4、测试

img