异常处理
# 异常处理
我们开发项目的时候,数据在请求过程中发生错误是非常常见的事情。
如:权限不足、数据唯一异常、数据不能为空异常、业务异常等。 这些异常如果不经过处理会对前端开发人员和使用者造成不便,因此我们就需要统一处理他们。
源码位于:源码位于:cutejava-framework 模块中的 cn.odboy.framework.exception 包中
# 异常封装
# 异常实体
@Data
class ApiError {
private Integer status;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Long timestamp;
private String message;
private ApiError() {
timestamp = System.currentTimeMillis();
}
public ApiError(Integer status,String message) {
this();
this.status = status;
this.message = message;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 自定义异常
# 1、通用异常
封装了 BadRequestException,用于处理通用的异常
@Getter
public class BadRequestException extends RuntimeException{
private Integer status = BAD_REQUEST.value();
public BadRequestException(String msg){
super(msg);
}
public BadRequestException(HttpStatus status,String msg){
super(msg);
this.status = status.value();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 全局异常拦截
使用全局异常处理器 @RestControllerAdvice 处理请求发送的异常
@RestControllerAdvice:默认会扫描指定包中所有@RequestMapping注解
@ExceptionHandler:通过@ExceptionHandler的 value 属性可过滤拦截的条件
# 具体使用
// 通用异常
throw new BadRequestException("发生了异常");
// 通用异常,使用自定义状态码
throw new BadRequestException(HttpStatus.OK, "发送了异常");
1
2
3
4
2
3
4
帮助我们改善此页面! (opens new window)