将 Try 转换为 Future 并将 recoverWith 转换为 Future

Convert Try to Future and recoverWith as Future

我有一个 Try 抛出异常。我希望 Try 变成 Future 这样我就可以 recoverWith.

如何在不处理 Try 中的任何异常的情况下将 Try 转换为 Future(仅在将来恢复)?

注意需要Await来测试你未来的结果

代码示例展示了我的想法,但一旦达到它也会抛出(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"))

您也可以 recoverWithTry

Try上使用maprecover方法分别生成Future.successfulFuture.failed,然后在[=13=上使用get ]

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)
 }

... how do convert Try to Future without handling any exception in the 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

没有必要介绍 Future 如果你只想使用 recoverWith(有点像 flatMap) 在你的 Try 对象上。

你可以这样:

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
 // 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)
 }