我有一个 Try
抛出异常。我想要那个 Try
成为Future
这样我就可以 recoverWith
.
我如何转换 Try
成Future
不处理 Try
中的任何异常(只是在 future 与恢复)?
请注意,需要使用 Await 来测试您 future 的结果
代码示例演示了我的想法,但一旦达到它也会抛出(new RuntimeException("-------failed-------")
是我得到的)
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"))
最佳答案
... how do convert
Try
toFuture
without handling any exception in theTry
?
使用
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
关于scala - 将尝试转换为 future 并恢复为 future ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39581921/