我的项目中有很长的可完成期货链,每个步骤都调用一个后端API,该API可以给出多个错误响应和一个成功响应。现在,在解析响应之后,我需要判断是否是错误,然后需要向用户显示。我还需要知道链中哪个阶段产生了此错误。
我现在的方法(如下所示)是每当我遇到错误响应时抛出运行时异常,然后将异常块附加到我的链中。我觉得这不是最好的方法,因为运行时异常不适用于这种情况。这也使我的代码很难看,因为每当我处理响应时都必须这样做,从而导致额外的异常检查。有更好的方法吗?
CompletableFuture.supplyAsync(() -> {
//some api call
Response response = request.send();
if(response.hasError()){ //this is what I am doing right now
logger.error("this is error response");
throw new ResponseErrorException("Error response received for request");
}
})
基本上,对链中的每个步骤都重复此操作。
摘要:如果在CompletableFuture链的任何步骤中都收到失败响应,那么将其传播给用户的好方法是什么?
编辑:如果没有更好的方法,请随时分享您对我的方法的看法。
答案 0 :(得分:2)
我的建议是对回复使用Decorator模式。建议您有这样的东西
CompletableFuture
.supplyAsync(() -> {
//some api call
Response response = request.send();
if(response.hasError()){ //this is what I am doing right now
throw new ResponseErrorException("Error response received for request");
}
})
.thenApply(() -> {
//some api call
Response response = request.send();
if(response.hasError()){ //this is what I am doing right now
throw new ResponseErrorException("Another Error response received for request");
}
})
.exceptionally(ex -> "Error: " + ex.getMessage());
如果您想避免重复抛出异常,可以使用以下方法
CompletableFuture
.supplyAsync(() -> {
//some api call
Response response = ThrowExceptionOnErrorResponse(request.send());
})
.thenApply(() -> {
//some api call
Response response = ThrowExceptionOnErrorResponse(request.send());
}
})
.exceptionally(ex -> "Error: " + ex.getMessage());
class ThrowExceptionOnError implements Response {
Response originalResponse;
ThrowExceptionOnError(Response originalResp) {
if(response.hasError()) {
throw new ResponseErrorException("Another Error response received for request");
}
this.originalResponse = originalResponse;
}