我看到CompletableFuture
有一个方法handle
与 scala 相同Future
's handle
基本上将成功和异常全部转换为成功map
and flatMap
上游(或thenApply
and thenCompose
在Java世界中)。
twitter 未来相当于什么rescue
(或 scala 未来recoverWith
)在java中呢?
rescue
在scala中基本上就像旧的javatry....catch
,然后重新抛出更多信息,以便更好地使用。例如在twitterFuture.handle
or scalaFuture.recover
返回单位是U
所以你返回一个响应。在twitterFuture.rescue
or scalaFuture.recoverWith
,它返回Future[U]
这样就可以接受某些例外情况,添加更多信息并返回Future.exception(xxxxx)
For recover
,如果您不需要返回超类并想要吞下所有异常,您可以使用exceptionally https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#exceptionally-java.util.function.Function-:
CompletableFuture<T> future = ...;
CompletableFuture<T> newFuture = future.exceptionally(_exc -> defaultValue);
否则,您需要使用handle https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#handle-java.util.function.BiFunction-得到一个CompletableFuture<CompletableFuture<U>>
,然后使用thenCompose https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#thenCompose-java.util.function.Function-折叠它:
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());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)