如何在Scala中跟踪例外情况和嵌套期货的结果

问题描述 投票:0回答:1

我有一种情况,我想计算嵌套的期货。下面是场景:

def firstFuture(factor: Int): Future[Int] = Future {
    println("Running future 1")
    Thread.sleep(3000)
    5 * factor
  }

  def secondFuture(factor: Int) = Future {
    println("Running future 2")
    throw new Exception("fjdfj")
    Thread.sleep(4000); 3 * factor
  }

  def thirdFuture = Future {
    println("Running future 3")
    Thread.sleep(5000)
    throw new Exception("mai fat raha hu")
  }

  def method = {
    (Future(5).map { factor =>
      firstFuture(factor).recover { case ex: Exception => throw new Exception("First future failed") }
      secondFuture(factor).recover { case ex: Exception => throw new Exception("Second future failed") }
      thirdFuture.recover { case ex: Exception => throw new Exception("Third future failed") }
    }).flatMap(identity).recover { case ex: Exception =>
      println("Inside recover")
      println(ex.getMessage)
    }
  }
  Await.result(method, 20 seconds)

我想处理主要将来完成的所有嵌套将来的例外。假设secondFuture失败,那么结果应该为secondFuture失败。但是我只是在第三未来得到了反映。我怎样才能做到这一点。应该执行什么。

注意:嵌套的三个期货应该并行运行。

scala future
1个回答
0
投票

您之所以只得到第三未来的错误,是因为整个块的值是该块的最后一个表达式,所以

Future(5).map { factor =>
  firstFuture(factor)   // this executes but the result is discarded
  secondFuture(factor)  // this executes but the result is discarded
  thirdFuture           // the last expression becomes the value of the whole block
}

为了满足您的要求,请尝试将理解力与Future#sequenceFuture#sequence,]结合使用>

for example

传递给for { factor <- Future(5) results <- Future.sequence(List(firstFuture(factor), secondFuture(factor), thirdFuture)) } yield results 的三个期货将同时执行,并且如果其中任何一个失败,sequence将返回失败的期货。

© www.soinside.com 2019 - 2024. All rights reserved.