代码
public class Result<T> {
@Getter
private boolean isSucceed = true;
@Getter
@Setter
private Integer code;
@Getter
@Setter
private String message;
@Getter
private Throwable throwable;
@Getter
@Setter
private T data;
public void setThrowable(Throwable throwable) {
isSucceed=false;
this.throwable = throwable;
}
}
public abstract class ResultBuilder {
public static <T> Result<T> builder(ParamVerification paramVerification,ResultWrraper<T> resultWrraper) throws Throwable {
Throwable throwable=paramVerification.checkParam();
if(null!=throwable){
throw throwable;
}
Result<T> result=new Result();
try {
T t =resultWrraper.wrraper();
result.setData(t);
}catch (Exception e){
result.setThrowable(e);
}
return result;
}
public interface ResultWrraper<T>{
/**
*
* @return
*/
T wrraper();
}
}
public interface ParamVerification {
Throwable checkParam();
}
测试代码
public class ResultBuilderTest {
@Test
public void builder() {
final String s="123";
Result<String> result;
try{
result=ResultBuilder.builder(() ->{
if (StringUtils.isBlank("")){
return new Exception("s is blank");
}
return null;
},()->{
return "test";
});
}catch (Throwable throwable){
System.out.printf(throwable.getMessage());
}
try {
result=ResultBuilder.builder(() ->{
if (StringUtils.isBlank(s)){
return new Exception("s is blank");
}
return null;
},()->{
return "test";
});
System.out.printf(result.getData());
Assert.assertEquals(result.getData(),"test");
}catch (Throwable throwable){
System.out.printf(throwable.getMessage());
}
}
}
测试结果:
源码:
https://gitee.com/able_yang/qitech-shop.git