统一响应格式类

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

public class Resp<T> {

//服务端返回的错误码
private int code=200;
//服务端返回的错误信息
private String msg="success";
//服务端返回的数据
private T data;

private Resp(int code,String msg,T data){
this.code=code;
this.msg=msg;
this.data=data;
}

public static <T> Resp success(T data){
Resp<T> resp = new Resp<>(200, "success", data);
return resp;
}


public static <T> Resp success(String msg,T data){
Resp resp = new Resp(200, msg, data);
return resp;
}

public static <T> Resp error(AppExceptionCodeMsg appExceptionCodeMsg){
Resp resp = new Resp(appExceptionCodeMsg.getCode(), appExceptionCodeMsg.getMsg(), null);
return resp;
}

public static <T> Resp error(int code,String msg){
Resp resp = new Resp(code, msg, null);
return resp;
}

public int getCode(){
return code;
}

public String getMsg(){
return msg;
}

public String toJsonString() {
return JSON.toJSONString(this);
}

@Override
public String toString() {
return "Resp{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}


}

全局异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

/**
* 处理所有未被其他异常处理方法处理的异常。
* 如果异常是 AppException 类型,则返回该异常中定义的错误码和错误信息;
* 如果异常不是 AppException 类型,则打印异常堆栈跟踪信息,并返回服务器端异常的默认错误码和错误信息。
* @param e 异常对象
* @return 包含错误码和错误信息的 Resp 对象
*/
@ExceptionHandler(value = {Exception.class})
@ResponseBody
public <T> Resp<T> exceptionHandler(Exception e){
if (e instanceof AppException){
AppException appException = (AppException) e;
return Resp.error(appException.getCode(),appException.getMsg());
}
String stackTrace = ExceptionUtil.getStackTrace(e);
log.error("服务器端异常,堆栈跟踪信息:" + stackTrace);
return Resp.error(500,"服务器端异常,堆栈跟踪信息:" + stackTrace);
}
}

自定义异常类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Getter
public class AppException extends RuntimeException{
private int code=500;
private String msg="服务器异常";

public AppException(AppExceptionCodeMsg appExceptionCodeMsg){
super();
this.code=appExceptionCodeMsg.getCode();
this.msg=appExceptionCodeMsg.getMsg();
}

public AppException(int code,String msg){
super();
this.code=code;
this.msg=msg;
}

}

自定义异常枚举类

1
2
3
4
5
6
7
8
9
10
11
12
@Getter
@AllArgsConstructor
public enum AppExceptionCodeMsg {

INVALID_CODE(10000,"验证码无效");
;

private int code;
private String msg;

}

用法

1
2
3
4
5
6
7
8
9
10
11
12
13
@RestController
public class DemoController{

@GetMapping("demo")
public Resp<String> demo1(String demo){
if("ok".equals(name)){
return Resp.success("succ");
}
if("error".equals(name)){
throw new AppException(AppExceptionCodeMsg.INVALID_CODE);
}
}
}