You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
2.5 KiB
77 lines
2.5 KiB
package com.example.demo.domain.vo;
|
|
|
|
import com.example.demo.Util.BusinessException;
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import lombok.AllArgsConstructor;
|
|
import lombok.Data;
|
|
import lombok.NoArgsConstructor;
|
|
|
|
|
|
import java.io.Serializable;
|
|
import java.util.HashMap;
|
|
|
|
@Data
|
|
@NoArgsConstructor
|
|
@AllArgsConstructor
|
|
public class Result implements Serializable {
|
|
private static final long serialVersionUID = 1L;
|
|
private Integer code; // 响应码,200 代表成功;401 代表未授权
|
|
private String msg; // 响应消息
|
|
private Object data; // 返回的数据
|
|
|
|
// 成功响应(不需要给前端返回数据)
|
|
public static Result success() {
|
|
return new Result(200, "success", new HashMap<>());
|
|
}
|
|
|
|
// 查询成功响应(把查询结果作为返回数据响应给前端)
|
|
public static Result success(Object data) {
|
|
return new Result(200, "success", data);
|
|
}
|
|
|
|
// 失败响应
|
|
public static Result error(String msg) {
|
|
return new Result(0, msg, new HashMap<>());
|
|
}
|
|
|
|
// 失败响应,可以自定义错误码
|
|
public static Result error(int code, String msg) {
|
|
return new Result(code, msg, new HashMap<>());
|
|
}
|
|
|
|
// 成功响应,可以自定义消息和数据
|
|
public static Result success(String msg, HashMap<String, Object> resultData) {
|
|
return new Result(200, msg, resultData); // 返回成功响应,状态码为 200
|
|
}
|
|
|
|
// 未授权响应,可以自定义错误码
|
|
public static Result unauthorized(int code, String msg) {
|
|
return new Result(code, msg, new HashMap<>());
|
|
}
|
|
|
|
// 错误响应,状态码为200,code为401
|
|
public static Result unauthorized(String msg) {
|
|
return new Result(401, msg, new HashMap<>());
|
|
}
|
|
|
|
//失败响应 自定义状态码 默认为500
|
|
public static Result error(BusinessException e) {
|
|
Result response = new Result();
|
|
// 定义默认错误码映射
|
|
final int defaultErrorCode = 400;
|
|
// 检查 getCode() 是否为 null(如果是 Integer)
|
|
Integer code = e.getCode();
|
|
if (code == null || code == 0) {
|
|
response.setCode(defaultErrorCode); // 默认错误码
|
|
} else {
|
|
response.setCode(code);
|
|
}
|
|
response.setMsg(e.getMessage());
|
|
return response;
|
|
}
|
|
public String toJson() throws JsonProcessingException {
|
|
ObjectMapper mapper = new ObjectMapper();
|
|
return mapper.writeValueAsString(this);
|
|
}
|
|
}
|