scala - 如何在失败的情况下使用多个期货
问题描述
我有一个带有两条消息的参与者,首先负责在 mongoDB 中插入数据,第二个参与者负责在 elasticsearch、InserInMongo 和 InserInES 中插入数据,即当 mongodb 插入操作失败或 ES 插入操作由于某些异常而失败时,会出现这种情况,并且我正在做这样的事情
try {
val mongoFuture: Future[Boolean] = ask(artGroupPersistenceActor, PersistArtGroupInMongo(artGroup)).mapTo[Boolean]
val esFuture: Future[Boolean] = ask(artGroupPersistenceActor, PersistArtGroupInES(artGroup)).mapTo[Boolean]
val resultMongo = Await.result(mongoFuture, timeout.duration)
log.debug("store: Record Inserted inserted in mongoDB {}", resultMongo)
val resultES = Await.result(esFuture, timeout.duration)
log.debug("store: Record Inserted in ES {}", resultES)
}
catch {
case e: Exception =>
log.error("store:While inserting an artgroup Exception in artGroupPersistenceActor actor", e)
throw e
}
在这里我想如果 mongoFuture 失败然后我捕获它的异常并且它应该继续 esFuture
或者如果两个未来都失败了我得到两个异常我该如何存档这个场景?
解决方案
你可以这样试试。
for {
x <- Future.successful {
try {
code here...
} catch {
case _: Exception =>
println("Error Inserting In Mongo ")
false
}
}
y <- Future.successful {
try {
code here...
// throw new IllegalStateException("Exception thrown")
} catch {
case _: IllegalStateException =>
println("Error Inserting In ES ")
false
}
}
} yield(x, y)
现在,如果在执行此过程时发生错误,您可以进行操作。祝您好运。
推荐阅读
- javascript - 如何将语音标记输出转换为 Amazon Polly 中的 JSON 对象数组?
- python - 可以一一安装包但不能使用 pip install -r requirements.txt
- java - 无法初始化类 org.codehaus.groovy.reflection.ReflectionCache
- asp.net - ASP.NET Core 运行时 3.1.9
- c# - C# 在控制台应用程序上异步并行下载多个文件时遇到问题
- node.js - Node.js - node-rsa - 加密期间出错。原始错误:错误:错误:0306E06C:bignumroutines:BN_mod_inverse:no inverse
- vue.js - 通天塔 - VueJS | 模块构建失败:错误:插件/预设文件不允许导出对象,只能导出函数。在
- java - 在Java和python实现中将数组转换为字符串
- kotlin - 以通用方式向函数添加副作用
- java - 如何在 Eclipse 中将文件夹标记为测试文件夹?