如何在scala中跟踪嵌套期货的异常和结果

如何在scala中跟踪嵌套期货的异常和结果,scala,error-handling,future,Scala,Error Handling,Future,我有一个想计算嵌套期货的场景。以下是场景: 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("

我有一个想计算嵌套期货的场景。以下是场景:

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失败。但我只是在第三个未来才考虑到这一点。我怎样才能做到这一点。应该如何实施


注意:嵌套的三个未来应该并行运行。

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

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(41).map { v =>
  Future(throw new RuntimeException("boom"))  // the exception is simply swallowed
  v + 1                                      
}
结果是
Future(42)
,尽管内部
Future
中抛出了异常。理解这一点很重要,否则我们可能会在系统中引入静默故障

为了达到您对理解和

用于{

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

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(41).map { v =>
  Future(throw new RuntimeException("boom"))  // the exception is simply swallowed
  v + 1                                      
}
结果是
Future(42)
,尽管内部
Future
中抛出了异常。这一点需要理解,否则我们可能会在系统中引入静默故障

为了达到您对理解和

用于{
因素