springboot3项目的搭建三(统一返回异常等)
一、统一返回 (其实两部分,一个是返回错误码可枚举可类,另一个是返回的实体其中data是泛型)
1.返回码:
package com.qiqi.common.constants; public enum ReturnCode { SUCCESS(200, "操作成功"), NEED_LOGIN(401, "需要登录后操作"), NO_OPERATOR_AUTH(403, "无权限操作"), TOKEN_ILL(404,"token非法"), SYSTEM_ERROR(500, "出现错误"), USERNAME_EXIST(501, "用户名已经存在"), PHOMENUMBER_EXIST(502, "手机号已存在"), EMAIL_EXIST(503, "邮箱已存在"), REQUEST_USERNAME(504, "必须填写用户名"), LOGIN_ERROR(505, "用户名或密码错误"); // 自定义状态码 private final int code; // 自定义描述 private final String msg; ReturnCode(int code, String errorMessage) { this.code = code; this.msg = errorMessage; } public int getCode() { return this.code; } public String getMsg() { return this.msg; } }
2.返回实体
package com.qiqi.common.response; import com.qiqi.common.constants.ReturnCode; import lombok.Data; import java.util.Objects; @Data public class ResultData<T> { /** * 响应编码 */ private Integer code; /** * 响应信息 */ private String msg; /** * 响应数据 */ private T data; /** * 接口请求时间 */ private long timestamp ; public ResultData(){ this.timestamp = System.currentTimeMillis(); } public ResultData(Integer code, String msg){ this.code=code; this.msg=msg; } public ResultData(Integer code, String msg, T data){ this.code=code; this.msg=msg; this.data=data; } public static ResultData success(){ return ResultData.success(ReturnCode.SUCCESS.getCode(),ReturnCode.SUCCESS.getMsg()); } public static ResultData success(int code, String msg){ ResultData<Object> resultData = new ResultData<>(); resultData.setCode(code); resultData.setMsg(msg); return resultData; } public static ResultData success(Object data){ ResultData<Object> resultData = new ResultData<>(ReturnCode.SUCCESS.getCode(),ReturnCode.SUCCESS.getMsg()); if (Objects.nonNull(data)){ resultData.setData(data); } return resultData; } public static ResultData error(int code, String msg){ ResultData<Object> resultData = new ResultData<>(code,msg); return resultData; } public static ResultData error(ReturnCode returnCode){ ResultData<Object> resultData = new ResultData<>(returnCode.getCode(), returnCode.getMsg()); return resultData; } }
3. 使用
//return ResultData.success(admins); //返回实体 return ResultData.error(ReturnCode.EMAIL_EXIST);//返回 邮箱已存在
二、异常处理
标签:返回,code,return,ResultData,springboot3,resultData,msg,public,搭建 From: https://www.cnblogs.com/fps2tao/p/18221640