What is java CompletableFuture equivalent of scala Future rescue and handle

旧巷老猫 提交于 2019-12-11 05:57:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!