springboot 同一返回结果
1、响应码枚举
package com.gaojiashun.enums;
public enum AppHttpCodeEnum {
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, "用户名或密码错误");
int code;
String msg;
AppHttpCodeEnum(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.itheima.reggie.common;
import com.itheima.reggie.enums.AppHttpCodeEnum;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Data
public class Result<T> {
/**
* 响应编码
*/
private Integer code;
/**
* 响应信息
*/
private String msg;
/**
* 响应数据
*/
private T data;
public Result(Integer code,String msg){
this.code=code;
this.msg=msg;
}
public Result(Integer code,String msg,T data){
this.code=code;
this.msg=msg;
this.data=data;
}
public static Result success(){
return Result.success(AppHttpCodeEnum.SUCCESS.getCode(),AppHttpCodeEnum.SUCCESS.getMessage());
}
public static Result success(int code,String msg){
Result<Object> result = new Result<>();
result.setCode(code);
result.setMsg(msg);
return result;
}
public static Result success(Object data){
Result<Object> result = new Result<>(AppHttpCodeEnum.SUCCESS.getCode(),AppHttpCodeEnum.SUCCESS.getMessage());
if (Objects.nonNull(data)){
result.setData(data);
}
return result;
}
public static Result error(int code,String msg){
Result<Object> result = new Result<>(code,msg);
return result;
}
public static Result error(AppHttpCodeEnum appHttpCodeEnum){
Result<Object> result = new Result<>(appHttpCodeEnum.getCode(), appHttpCodeEnum.getMessage());
return result;
}
}