Files
ipms-sjy/src/main/java/cn/iocoder/dashboard/common/pojo/CommonResult.java

103 lines
2.9 KiB
Java
Raw Normal View History

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