简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM