本文介绍了将Try转换为Future,然后将withWithWith转换为Future的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Try
引发异常.我希望 Try
成为 Future
,这样我就可以 recoverWith
.
I have a Try
that throws Exception. I want that Try
to become a Future
so I will be able to recoverWith
.
如何在不处理 Try
中的任何异常的情况下将 Try
转换为 Future
(正好在将来具有恢复功能)?
How can I convert the Try
into a Future
without handling any exceptions in the Try
(just in the Future with recover)?
请注意,需要Await来测试未来的结果
该代码示例演示了我的想法,但是一旦达到,它也会引发( new RuntimeException("------- failed -------")
是我得到了什么
The code sample demonstrates what I had in mind but it also throws once reached (new RuntimeException("-------failed-------")
is what I get)
val t = Try(throw new RuntimeException("my"))
val resF : Future[String] = if (t.isSuccess)
Future.successful(t.get)
else
Future.failed(new RuntimeException("-------failed-------"))
val resFWithRecover = resF.recoverWith{
case NonFatal(e) =>
Future.successful("recoveredWith")
}
Await.result(resFWithRecover, Duration("5s"))
推荐答案
使用 Future.fromTry
.
scala> val t = Try(throw new RuntimeException("my"))
t: scala.util.Try[Nothing] = Failure(java.lang.RuntimeException: my)
scala> val resF = Future.fromTry(t)
resF: scala.concurrent.Future[Nothing] = scala.concurrent.impl.Promise$KeptPromise@57cf54e1
scala> resF.recoverWith{
| case NonFatal(e) =>
| Future.successful("recoveredWith")
| }
res5: scala.concurrent.Future[String] = scala.concurrent.impl.Promise$DefaultPromise@1b75c2e3
这篇关于将Try转换为Future,然后将withWithWith转换为Future的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!