This commit is contained in:
seesaw
2024-09-27 11:23:59 +08:00
parent a8661ee306
commit 58e4d5d1d4
35 changed files with 1532 additions and 0 deletions

View File

@ -0,0 +1,115 @@
package cn.iocoder.yudao.framework.common.pojo;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.util.Assert;
import java.io.Serializable;
import java.util.Objects;
/**
* 通用返回
*
* @param <T> 数据泛型
*/
@Data
public class StoreResult<T> implements Serializable {
/**
* 错误码
*
* @see ErrorCode#getCode()
*/
private String statusCode;
/**
* 返回数据
*/
private T data;
/**
* 错误提示,用户可阅读
*
* @see ErrorCode#getMsg() ()
*/
private String message;
private Boolean success;
/**
* 将传入的 result 对象,转换成另外一个泛型结果的对象
*
* 因为 A 方法返回的 CommonResult 对象,不满足调用其的 B 方法的返回,所以需要进行转换。
*
* @param result 传入的 result 对象
* @param <T> 返回的泛型
* @return 新的 CommonResult 对象
*/
public static <T> StoreResult<T> error(StoreResult<?> result) {
return error(result.getStatusCode(), result.getMessage());
}
public static <T> StoreResult<T> error(String code, String message) {
Assert.isTrue(!GlobalErrorCodeConstants.SUCCESS.getCode().equals(code), "code 必须是错误的!");
StoreResult<T> result = new StoreResult<>();
result.statusCode = code;
result.message = message;
return result;
}
public static <T> StoreResult<T> error(ErrorCode errorCode) {
return error(errorCode.getCode().toString(), errorCode.getMsg());
}
public static <T> StoreResult<T> success(T data) {
StoreResult<T> result = new StoreResult<>();
result.statusCode = "200";
result.data = data;
result.message = "";
result.success = true;
return result;
}
public static boolean isSuccess(String code) {
return Objects.equals(code, GlobalErrorCodeConstants.SUCCESS.getCode().toString());
}
@JsonIgnore // 避免 jackson 序列化
public boolean isSuccess() {
return isSuccess(statusCode);
}
@JsonIgnore // 避免 jackson 序列化
public boolean isError() {
return !isSuccess();
}
// ========= 和 Exception 异常体系集成 =========
/**
* 判断是否有异常。如果有,则抛出 {@link ServiceException} 异常
*/
public void checkError() throws ServiceException {
if (isSuccess()) {
return;
}
// 业务异常
throw new ServiceException(Integer.valueOf(statusCode), message);
}
/**
* 判断是否有异常。如果有,则抛出 {@link ServiceException} 异常
* 如果没有,则返回 {@link #data} 数据
*/
@JsonIgnore // 避免 jackson 序列化
public T getCheckedData() {
checkError();
return data;
}
public static <T> StoreResult<T> error(ServiceException serviceException) {
return error(serviceException.getCode().toString(), serviceException.getMessage());
}
}