gpt4 book ai didi

scala - 如何在Scala中跟踪异常情况和嵌套 future 的结果

转载 作者:行者123 更新时间:2023-12-03 07:46:28 24 4
gpt4 key购买 nike

我有一种情况,我想计算嵌套的 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("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)

我要处理主要将来完成的所有嵌套将来的异常(exception)。假设secondFuture失败,那么结果应该为secondFuture失败。但是我只是在第三 future 得到了反射(reflect)。我怎样才能做到这一点。应该执行什么。

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

最佳答案

之所以只得到第三 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 并抛入内部 future 时会发生什么
Future(41).map { v =>
Future(throw new RuntimeException("boom")) // the exception is simply swallowed
v + 1
}

尽管内部 Future(42)内抛出异常,结果仍是 Future。了解这一点很重要,因为否则我们可能会在系统中引入 静默失败

满足您的要求 try理解和 Future.sequence 的组合
for {
factor <- Future(5)
results <- Future.sequence(List(firstFuture(factor), secondFuture(factor), thirdFuture))
} yield results

传递给 sequence的三个Future将同时执行,如果其中任何一个失败, sequence将返回失败的Future。

关于scala - 如何在Scala中跟踪异常情况和嵌套 future 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61478147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com