自定义异常处理器
自定义异常处理器
案例
自定义异常类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42package com.xw.yygh.common.exception;
/**
* 自定义全局异常类
*
* @author qy
*/
@Data
@ApiModel(value = "自定义全局异常类")
public class YyghException extends RuntimeException {
@ApiModelProperty(value = "异常状态码")
private Integer code;
/**
* 通过状态码和错误消息创建异常对象
* @param message
* @param code
*/
public YyghException(String message, Integer code) {
super(message);
this.code = code;
}
/**
* 接收枚举类型对象
* @param resultCodeEnum
*/
public YyghException(ResultCodeEnum resultCodeEnum) {
super(resultCodeEnum.getMessage());
this.code = resultCodeEnum.getCode();
}
@Override
public String toString() {
return "YyghException{" +
"code=" + code +
", message=" + this.getMessage() +
'}';
}
}添加全局异常处理类
采用AOP实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21package com.xw.yygh.common.exception;
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
// 处理自定义异常
@ExceptionHandler(YyghException.class)
public Result error(YyghException e) {
e.printStackTrace();
return Result.fail();
}
// 处理Exception异常
@ExceptionHandler(Exception.class)
public Result error(Exception e) {
e.printStackTrace();
return Result.fail();
}
}
自定义异常处理器
http://xwww12.github.io/2022/10/11/spring/springboot/自定义异常处理器/