scala - 如何在scala中跟踪嵌套期货的异常和结果
问题描述
我有一个场景,我想计算嵌套期货。下面是场景:
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.sequence
for {
factor <- Future(5)
results <- Future.sequence(List(firstFuture(factor), secondFuture(factor), thirdFuture))
} yield results
传递给的三个期货sequence
将同时执行,sequence
如果其中任何一个失败,将返回失败的未来。
推荐阅读
- excel - VBA 将多个 Excel 文件转换为 CSV 并删除尾随逗号
- java - UUID 类型的轴突聚合标识符
- javascript - webRTC 中的额外列
- php - 尝试在 php 中使用 openssl_decrypt 解密数据,但在邮递员中没有得到任何输出
- python-3.x - 用正则表达式 python 查找 +- 1
- django - 如何创建管理命令以通过电子邮件发送密码重置?
- reactjs - 材料表反应 - 编辑期间禁用保存
- airflow - “字段:prediction_input.model_name 错误:名称应采用 'projects/your-project-id/models/your-model-name' 的形式”
- javascript - 无法在表单验证中读取未定义的属性“值”
- reactjs - 在更新组合减速器中的一个减速器状态时,防止其他减速器状态重置