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) {
SingleResponse<HashMap<String, Object>> response = getResponse(0);
if (response.isSuccess()) {
System.out.println(response);
}
HashMap<String, Object> data = ResponseUtil.unpack(getResponse(123));
System.out.println(data);
HashMap<String, Object> data2 = ResponseUtil.unpack(getResponse(0));
System.out.println(data2);
}
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) {
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>