[英]Convert Try to Future in scala and recoverWith as Future
[編輯]
*被問到我是新手。 這是答案:
Future.fromTry(Try( 1/0 ))
其他值得注意的事情(在檢查時可能會誤導我):
Future.successful( 1/0 )
一旦到達將拋出。 Future.successful和Future.failure不僅是創建Future的便捷方法,它們還跳過了執行上下文循環並按順序進行評估。
[原始問題]
我有一個Try
引發異常。 我希望Try
成為Future
這樣我就可以recoverWith
。
請不要猜測你是否不知道 。
現在的問題是,如何轉換Try
對Future
沒有處理任何異常的Try
(只是在恢復未來)?
請注意,需要等待才能測試您的未來結果
該代碼示例演示了我的想法,但是一旦達到就拋出了( 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"))
...如何在不處理
Try
任何異常的情況下將Try
轉換為Future
?
使用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對象上使用restoreWith (類似於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
// 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)
}
您可以在Try
也recoverWith
使用map
和recover
上的方法Try
生產Future.successful
和Future.failed
分別再get
上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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.