在开发中,需要使用API统一返回对象保证后端返回的数据是固定并有格式的,便于前端进行解析,返回相应的信息给用户,这就要求不管程序抛出任何错误或异常,你所返回的对象都应该是:
{
"status": ‘状态码’,
"msg": "信息",
“data”:“数据”
}
使用API统一返回对象的流程如下:
1、创建一个API统一返回对象的类:
该类应该包含status(状态码)、msg(信息)、data(数据);data的类型应设置为泛型,方便作为参数传输。并构造对应的get和set方法
定义成功的状态码、信息:
public class ApiRestResponse <T>{
private Integer status;
private String msg;
private T data;
private static final int OK_CODE = 10000;
private static final String OK_MSG = "success";
}
成功时,不需要返回数据的方法:
public ApiRestResponse(Integer status, String msg) {
this.status = status;
this.msg = msg;
}
public ApiRestResponse(){
this(OK_CODE,OK_MSG);
}
还需要一个返回数据的方法(包含成功和失败):
public ApiRestResponse(Integer status, String msg, T data) {
this.status = status;
this.msg = msg;
this.data = data;
}
//错误时返回错误编码和信息,传入异常枚举类,返回相应的code和msg
public static <T> ApiRestResponse<T> success(T result) {
ApiRestResponse<T> response = new ApiRestResponse<>();
response.setStatus((Integer) result);
return response;
}
完整的类:
public class ApiRestResponse <T>{
private Integer status;
private String msg;
private T data;
private static final int OK_CODE = 10000;
private static final String OK_MSG = "success";
public ApiRestResponse(Integer status, String msg, T data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public ApiRestResponse(Integer status, String msg) {
this.status = status;
this.msg = msg;
}
public ApiRestResponse(){
this(OK_CODE,OK_MSG);
}
// 成功时返回通用响应对象
public static <T> ApiRestResponse<T> success(){
return new ApiRestResponse<>();
}
public static <T> ApiRestResponse<T> success(T result) {
ApiRestResponse<T> response = new ApiRestResponse<>();
response.setData(result);
return response;
}
// 错误时返回错误编码和信息,传入异常枚举类,返回相应的code和msg
public static <T> ApiRestResponse<T> error(PlatformExceptionEnum ex){
return new ApiRestResponse<>(ex.getCode(), ex.getMsg());
}
public static <T> ApiRestResponse<T> error(Integer code, String msg) {
return new ApiRestResponse<>(code, msg);
}
@Override
public String toString() {
return "ApiRestResponse{" +
"status=" + status +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Integer getStatus() {
return status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setStatus(Integer status) {
this.status = status;
}
}
在上面这个类中,PlatformExceptionEnum ex是自定义的统一异常类,根据不同的情况返回不同的信息和状态码。
代码如下:
public class PlatformException extends Exception{
private final Integer code;
private final String message;
public PlatformException(Integer code, String message) {
this.code = code;
this.message = message;
}
public PlatformException(PlatformExceptionEnum exceptionEnum){
this(exceptionEnum.getCode(), exceptionEnum.getMsg());
}
public Integer getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
}