Search code examples
scalaconcurrencyfuture

Convert Try to Future and recoverWith as Future


I have a Try that throws Exception. I want that Try to become a Future so I will be able to recoverWith.

How can I convert the Try into a Future without handling any exceptions in the Try (just in the Future with recover)?

note that Await is needed to test the result of your future

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

Solution

  • ... how do convert Try to Future without handling any exception in the Try?

    Use 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