简体   繁体   English

CompletableFuture的单独异常处理

[英]Separated exception handling of a CompletableFuture

I realize that I'd like the consumers of our API to not have to handle an exception. 我意识到我希望我们的API的消费者不必处理异常。 Or perhaps more clearly I'd like to ensure that the exception is always logged, but only the consumer will know how to handle success. 或者更清楚一点,我想确保始终记录异常,但只有消费者才知道如何处理成功。 I want the client to be able to handle the exception as well if they want, There is no valid File that I could return to them. 我希望客户端能够处理异常,如果他们想要的话,没有有效的File我可以返回给他们。

Note: FileDownload is a Supplier<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;

}

I don't really understand the CompletionStage stuff. 我真的不了解CompletionStage东西。 Do I use exception or handle ? 我是否使用exceptionhandle do I return the original future or the future they return? 我会回归原来的未来还是他们回来的未来?

Assuming that you do not want to affect the result of your CompletableFuture , you'll want to use CompletableFuture::whenComplete : 假设您不想影响CompletableFuture的结果,您将需要使用CompletableFuture::whenComplete

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

Now when the consumer of your API tries to call future.get() , they will get an exception, but they don't necessarily need to do anything with it. 现在,当您的API的使用者尝试调用future.get() ,他们将获得异常,但他们不一定需要对其执行任何操作。


However, if you want to keep your consumer ignorant of the exception (return null when the fileDownload fails), you can use either CompletableFuture::handle or CompletableFuture::exceptionally : 但是,如果您希望让消费者不知道异常(当fileDownload失败时返回null ),您可以使用CompletableFuture::handleCompletableFuture::exceptionally

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM