Scala 将Try转换为Future并恢复为Future
我有一个Scala 将Try转换为Future并恢复为Future,scala,concurrency,future,Scala,Concurrency,Future,我有一个Try抛出异常。我希望尝试成为的未来,这样我就能够恢复 如何将Try转换为Future,而不处理Try中的任何异常(仅在将来使用recover) 请注意,等待是测试未来结果所必需的 代码示例演示了我的想法,但它也会在到达时抛出(newruntimeexception(“----failed------”)就是我得到的) 您也可以在上使用恢复 分别使用Try上的map和recover方法生成未来。成功的和未来。失败的,然后在Try上获取 val future = Try { th
Try
抛出异常。我希望尝试成为的未来
,这样我就能够恢复
如何将Try
转换为Future
,而不处理Try
中的任何异常(仅在将来使用recover)
请注意,等待是测试未来结果所必需的
代码示例演示了我的想法,但它也会在到达时抛出(newruntimeexception(“----failed------”)
就是我得到的)
您也可以在上使用恢复
分别使用Try
上的map
和recover
方法生成未来。成功的和未来。失败的,然后在Try
上获取
val future =
Try {
throw new Exception("explosion")
}.map { result =>
Future.successful(result)
}.recover { case th =>
Future.failed(th)
}.get
使用模式匹配
val future =
Try {
throw new Exception("something")
} match {
case Success(value) => Future.successful(value)
case Failure(th) => Future.failed(th)
}
。。。如何将Try
转换为Future
,而不处理Try
中的任何异常
使用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对象上使用recoverWith(有点像flatMap),则无需引入Future
您可以这样做,如下所示:
val t = Try[String](throw new RuntimeException("my"))
val u = t.recoverWith{
case e => Success(s"ignoring exception ${e.getLocalizedMessage}")
}
u.foreach(println(_))
这将导致控制台的以下输出:
ignoring exception my
请用“doSomething()”这个“扔”字,你就不能通过“}.get”谢谢。现在将recoverWith添加到该未来并“等待”。您仍然会有一个异常,而不是recoverdrunning:val res=Await.result(resF,Duration(“1s”))将抛出exception@ozma,不要在resF
上等待
。而是等待recoverWith
返回的内容。换句话说,val resRW=resF.recoverWith{…}
,然后wait.result(resRW,
@jwvh这就是我所做的(现在将其添加到代码示例中)@ozma,您的代码示例不使用fromTry()
正如m-z所建议的那样。我的测试表明m-z的代码是有效的。你只需在正确的未来
上等待
,也就是说,不是从fromTry()
返回的代码,而是从recoverWith()
fromTry()之后返回的代码
@ozma首先,如果你只是想用Await
进行阻止,为什么还要麻烦使用Future
s呢?这毫无意义。其次,如果你要使用Await
,你需要在最后一次Future
上进行操作,也就是调用recoverWith
的结果。在我的例子中,你需要等待res5de>,而不是resF
。即等待.result(resF.recoverWith{…},Duration.Inf)
。未来是不可变的。恢复resF
不会改变resF
,它会创建一个新的Future
。谢谢,但这不是我的问题。我需要保留一个返回Future的接口,我需要它像一个接口一样运行。我想,你的意思是“f2=f match{…”。它没有为我编译。请添加正确导入的完整示例。谢谢。
ignoring exception my
// you need to provide your try with type information in lhs
// as the rhs is not providing any type info
val t: Try[String] = Try(throw new RuntimeException("my"))
// Now you can easily get a Future[String] from this Try[String]
val f = Future.fromTry(t)
// or you can use pattern matching
val f2 = t match {
case Success(str) => Future.succesful(str)
case Failure(ex) => Future.failed(ex)
}