CheckParamAssert 类
import org.springframework.util.ObjectUtils;
import java.util.Objects;
/**
* 检查参数(对象)的断言工具,不满足条件则快速报错
*/
public class CheckParamAssert {
public static void notEmpty(Object param, String errorMsg) {
if (ObjectUtils.isEmpty(param)) {
throw new CheckParamException(errorMsg);
}
}
public static void isTrue(Boolean condition, String errorMsg) {
if (!condition) {
throw new CheckParamException(errorMsg);
}
}
}
值得注意的是, ObjectUtils.isEmpty() 是导自org.springframework.util.ObjectUtils,几乎涵盖了所有的常见Java对象
下面为这个方法isEmpty的主要代码:
public static boolean isEmpty(@Nullable Object obj) {
if (obj == null) {
return true;
} else if (obj instanceof Optional) {
return !((Optional)obj).isPresent();
} else if (obj instanceof CharSequence) {
return ((CharSequence)obj).length() == 0;
} else if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
} else if (obj instanceof Collection) {
return ((Collection)obj).isEmpty();
} else {
return obj instanceof Map ? ((Map)obj).isEmpty() : false;
}
}
自定义异常类 CheckParamException
import lombok.Data;
import org.springframework.util.StringUtils;
/**
* 业务错误自定义异常类,code表示报错编码: 404、500、505之类的, 暂用不到
*/
@Data
public class CheckParamException extends RuntimeException {
private String message;
private String code;
public CheckParamException() {
}
public CheckParamException(String message) {
super(message);
this.message = message;
}
public CheckParamException(String code, String message) {
super( message);
this.message = message;
this.code = code;
}
public CheckParamException(Throwable cause, String message) {
super(message,cause);
this.message = message;
}
private void setErrorMessage(String errorMessage){
String errDesc = "";
if(StringUtils.isEmpty(errorMessage)){
this.message = errDesc;
}else{
this.message = errorMessage;
}
}
}