如何处理CompletableFutures链错误响应?

问题描述 投票:3回答:1

我有completable期货的长链在我的项目,每一步调用后端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链的步骤的失败响应,什么是它传播到用户的好办法?

编辑:如果没有更好的办法,请随时在我的方法分享您的意见。

java asynchronous exception exception-handling completable-future
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.