首页 > 解决方案 > 如何在失败的情况下使用多个期货

问题描述

我有一个带有两条消息的参与者,首先负责在 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

或者如果两个未来都失败了我得到两个异常我该如何存档这个场景?

标签: scalaakkafuture

解决方案


你可以这样试试。

    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)

现在,如果在执行此过程时发生错误,您可以进行操作。祝您好运。


推荐阅读