gpt4 book ai didi

java - CompletableFuture 的分离异常处理

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:38:12 24 4
gpt4 key购买 nike

我意识到我希望我们 API 的使用者不必处理异常。或者更明确地说,我想确保始终记录异常,但只有消费者知道如何处理成功。我希望客户端也能够根据需要处理异常,没有有效的 File我可以回到他们身边。

备注:FileDownloadSupplier<File>

@Override
public CompletableFuture<File> processDownload( final FileDownload fileDownload ) {
Objects.requireNonNull( fileDownload );
fileDownload.setDirectory( getTmpDirectoryPath() );
CompletableFuture<File> future = CompletableFuture.supplyAsync( fileDownload, executorService );
future... throwable -> {
if ( throwable != null ) {
logError( throwable );
}
...
return null; // client won't receive file.
} );
return future;

}

我不太明白 CompletionStage东西。我使用 exception 吗?或 handle ?我返回原来的 future 还是他们返回的 future ?

最佳答案

假设您不想影响CompletableFuture 的结果,您将需要使用CompletableFuture::whenComplete。 :

future = future.whenComplete((t, ex) -> {
if (ex != null) {
logException(ex);
}
});

现在,当您的 API 的使用者尝试调用 future.get() 时,他们会得到一个异常,但他们不一定需要对其执行任何操作。


但是,如果您想让您的消费者不知道异常(当 fileDownload 失败时返回 null),您可以使用 CompletableFuture::handleCompletableFuture::exceptionally :

future = future.handle((t, ex) -> {
if (ex != null) {
logException(ex);
return null;
} else {
return t;
}
});

future = future.exceptionally(ex -> {
logException(ex);
return null;
});

关于java - CompletableFuture 的分离异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37032990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com