问题
I see that CompletableFuture has a method handle that is the same as that of scala Future's handle basically converting success and exceptions all to success to be map and flatMap upstream(or thenApply and thenCompose in java world).
What is the equivalent of twitter future rescue(or scala future recoverWith) in java though?
rescue in scala is basically like the old java try....catch, then rethrow with more information so it can be nice to use. For example in twitterFuture.handle or scalaFuture.recover the return unit is U so you return a response. In twitterFuture.rescue or scalaFuture.recoverWith, it returns Future[U] so one can take certain exceptions, add more info and return Future.exception(xxxxx)
回答1:
For recover, if you don't need to return a superclass and want to swallow all exceptions, you could just use exceptionally:
CompletableFuture<T> future = ...;
CompletableFuture<T> newFuture = future.exceptionally(_exc -> defaultValue);
Otherwise, you need to use handle to get a CompletableFuture<CompletableFuture<U>>, and then use thenCompose to collapse it:
CompletableFuture<T> future = ...;
CompletableFuture<T> newFuture = future.handle((v, e) -> {
if (e == null) {
return CompletableFuture.completedFuture(v);
} else {
// the real recoverWith part
return applyFutureOnTheException(e);
}
}).thenCompose(Function.identity());
来源:https://stackoverflow.com/questions/39940494/what-is-java-completablefuture-equivalent-of-scala-future-rescue-and-handle