简介
- 我们通常接触的项目大多已经是前后端分离的项目,前后端的数据交互往往封装成统一的JSON格式。
- 封装统一的响应体结构
{
"code" : 20000,
"message" : "操作成功",
"data" : null
}
- 统一的异常处理
我们使用@RestControllerAdvice
结合@ExceptionHandler
,并继承ResponseEntityExceptionHandler
支持web类的错误处理。
1. 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. 封装响应体
@Data
@Accessors(chain = true)
public class ResponseResult<T> implements Serializable {
private static final long serialVersionUID = -1L;
private Integer code;
private String message;
private T data;
public ResponseResult(Integer code, String message, T data) {
super();
this.code = code;
this.message = message;
this.data = data;
}
private static <T> ResponseResult<T> build(Integer code, String message, T data) {
return new ResponseResult<>(RespCode.OK.code, message, data);
}
public static <T> ResponseResult<T> ok(T data) {
return build(RespCode.OK.code, RespCode.OK.message, data);
}
private static <T> ResponseResult<T> ok(String message, T data) {
return build(RespCode.OK.code, message, data);
}
public static <T> ResponseResult<T> fail() {
return fail(RespCode.ERROR.message);
}
public static <T> ResponseResult<T> fail(String message) {
return fail(RespCode.ERROR, message);
}
public static <T> ResponseResult<T> fail(RespCode respCode, String message) {
return build(respCode.getCode(), message, null);
}
public enum RespCode {
OK(20000, "请求成功"),
MY_ERROR(20433, "自定义异常"),
UNAUTHORIZED(20401, "未授权"),
LOGIN_FAIL(20402, "账号或密码错误"),
ERROR(20400, "未知异常");
RespCode(int code, String message) {
this.code = code;
this.message = message;
}
private final int code;
private final String message;
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
}
3. 全局异常处理
@Slf4j
@RestControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(value = Exception.class)
public ResponseResult<String> defaultException(Exception e) {
if (e instanceof NullPointerException){
log.error("空指针异常:" + e.getMessage(), e);
return ResponseResult.fail("空指针异常");
}
log.error("未知异常:" + e.getMessage(), e);
return ResponseResult.fail();
}
}
4. 效果测试
@RestController
public class IndexController {
@GetMapping("/")
public ResponseResult<String> hello() {
return ResponseResult.ok("hello");
}
@GetMapping("/err")
public ResponseResult<String> error() {
int i = 1 / 0;
return ResponseResult.ok("模拟错误");
}
}
- 浏览器输入
ip:端口:/err
6. 源码分享