Search code examples
scalafuturerecover

Scala, recover nested Futures?


I have a few nested Futures in Scala. I am wondering -- can I use one recover to catch all throwables or should each Future have its own recover? Imagine that method1 and method2 produce both a Future[Option[A]],

method1.flatMap {

  case Some(object1) =>

    method2(object1).map {
      case Some(object2) => ...
      case None => ...
    }.recover { case t => .... } <--- DO I NEED THIS?

  case None => ....

}.recover { case t => ... } <--- OR THIS ALONE IS ENOUGH?

Solution

  • As long as you flattens all nested Futures as you do in your example, it does not matter at which level the exception is thrown. If an exception is thrown at some point in your nesting structure, then you'll stop descending further down. Due to the flattening the thrown exception will then be heaved up to the top level. From there you can treat the exception with the recover method.