ResponseUtil 减少代码行数
ResponseUtil
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.SysException;
import java.util.HashMap;
import java.util.function.Supplier;
public class ResponseUtil {
public static void main(String[] args) {
//当 feign 调用 Response响应不为success 时 不抛异常的情况 自行判断,不用调用 unpack 解包
SingleResponse<HashMap<String, Object>> response = getResponse(0);
if (response.isSuccess()) {
System.out.println(response);
}
//当 feign 调用 Response响应不为success 时 直接抛异常
HashMap<String, Object> data = ResponseUtil.unpack(getResponse(123));
System.out.println(data);
HashMap<String, Object> data2 = ResponseUtil.unpack(getResponse(0));
System.out.println(data2);
}
/**
* 模拟feign 调用
* @param i
* @return
*/
private static SingleResponse<HashMap<String, Object>> getResponse(int i) {
if (i == 0) {
return SingleResponse.buildFailure("入参为0调用不成功 code", "入参为0调用不成功 errMessage");
}
HashMap<String, Object> map = new HashMap<>();
SingleResponse<HashMap<String, Object>> response = SingleResponse.of(map);
map.put("1111111111111", i);
return response;
}
/**
* 解包
*/
public static <T> T unpack(SingleResponse<T> singleResponse) {
//todo 需要根绝实际情况修改 SysException
return unpackOrElseThrow(singleResponse, () -> new SysException("feign调用 Response 响应不成功 code todo", "feign调用 Response 响应不成功 errMessage todo"));
}
public static <X extends Throwable, T> T unpackOrElseThrow(SingleResponse<T> singleResponse, Supplier<? extends X> exceptionSupplier) throws X {
if (singleResponse.isSuccess()) {
return singleResponse.getData();
} else {
throw exceptionSupplier.get();
}
}
}
maven依赖
<dependency>
<groupId>com.alibaba.cola</groupId>
<artifactId>cola-component-dto</artifactId>
<version>4.3.2</version>
</dependency>
<dependency>
<groupId>com.alibaba.cola</groupId>
<artifactId>cola-component-exception</artifactId>
<version>4.3.2</version>
</dependency>
浏览 (684)
点赞 (1)
收藏