我意识到我希望API的使用者不必处理异常。或者更清楚地说,我希望确保异常总是被记录下来,但只有消费者知道如何处理成功。我希望客户端能够处理异常,如果他们愿意的话,没有有效的File可以返回给他们。
注意:FileDownload是一个Supplier<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?我是返回原始的未来,还是他们返回的未来?
发布于 2016-05-05 00:25:34
假设您不想影响CompletableFuture的结果,那么您将希望使用CompletableFuture::whenComplete
future = future.whenComplete((t, ex) -> {
if (ex != null) {
logException(ex);
}
});现在,当你的应用程序接口的使用者试图调用future.get()时,他们会得到一个异常,但他们不一定需要对它做任何事情。
但是,如果您想让您的使用者对异常一无所知(当fileDownload失败时返回null ),您可以使用CompletableFuture::handle或CompletableFuture::exceptionally
future = future.handle((t, ex) -> {
if (ex != null) {
logException(ex);
return null;
} else {
return t;
}
});或
future = future.exceptionally(ex -> {
logException(ex);
return null;
});https://stackoverflow.com/questions/37032990
复制相似问题