通用返回类设计(Java)
通用返回类
一般后端需要将数据封装成通用返回类再传递给前端
/**
* 通用返回类
* @param <T>
*/
@Data
public class BaseResponse<T> implements Serializable {
//状态码
private int code;
//数据
private T data;
//状态码信息
private String message;
//状态码描述
private String description;
public BaseResponse(int code, T data, String message,String description) {
this.code = code;
this.data = data;
this.message = message;
this.description = description;
}
public BaseResponse(int code, T data,String message) {
this(code,data,"","");
}
public BaseResponse(int code, T data) {
this(code,data,"","");
}
public BaseResponse(ErrorCode errorCode) {
this(errorCode.getCode(),null,errorCode.getMessage(),errorCode.getDescription());
}
}
返回工具类,定义成功/失败方法
/**
* 返回工具类
*/
public class ResultUtils {
/**
* 成功
* @param data
* @return
*/
public static <T> BaseResponse<T> success(T data){
return new BaseResponse<>(0,data,"ok");
}
/**
* 失败
* @param errorCode
* @return
*/
public static BaseResponse error(ErrorCode errorCode){
return new BaseResponse<>(errorCode);
}
public static BaseResponse error(ErrorCode errorCode,String message,String description){
return new BaseResponse<>(errorCode.getCode(),message,description);
}
public static BaseResponse error(int code,String message,String description){
return new BaseResponse<>(code,null,message,description);
}
public static BaseResponse error(ErrorCode errorCode,String description){
return new BaseResponse<>(errorCode.getCode(),errorCode.getMessage(),description);
}
}
用枚举定义错误码,统一成功/失败的信息
/**
* 错误码
*/
public enum ErrorCode {
/**
* 返回异常枚举类
*/
SUCCESS(0, "OK", ""),
PARAMS_ERROR(40000, "请求参数错误", ""),
NULL_ERROR(40001, "请求数据为空", ""),
NOT_LOGIN(40100, "未登录", ""),
NO_AUTH(40101, "无权限", ""),
SYSTEM_ERROR(50000, "系统内部异常", "");
/**
* 状态码
*/
private int code;
/**
* 状态码信息
*/
private String message;
/**
* 状态码描述(详情)
*/
private String description;
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public String getDescription() {
return description;
}
ErrorCode(int code, String message, String description) {
this.code = code;
this.message = message;
this.description = description;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?