在Scala中返回Future.failed(new Exception(""))时继续

ann*_*iid 7 scala

如果未来返回失败的异常,我该如何处理?

场景是我的代码调用getValue(),将结果映射到verifyValue()然后我希望能够处理getValue()的结果的情况Future.failed(new Exception("message")).但是当我运行它时,如果getValue()的结果是失败的未来,它只会抛出异常而不是处理异常.

有没有人对我怎么做这个有什么建议?

def method(): Future[JsObject] = {
    getValue().flatMap(verifyValue(_))
}

def getValue(): Future[JsObject] = {
    try {
        value1 <- getValue1()
        value2 <- getValue2(value1)
    } yield {
        value2
    }
}

def verifyValue(result: Any): Future[JsObject] = {
  result match {
    case e: Exception =>
      getValue()
    case json: JsObject => Future.successful(json)
  }
}
Run Code Online (Sandbox Code Playgroud)

更新:我认为我没有用原始问题说明这一点,但我之所以平面化这个值是因为我不想明确地等待代码中的任何期货,因此我不知道我想使用Future.onComplete {}来解析这个值.

更新2:另一件可能不太清楚的事情是,如果它抛出异常,我想调用另一种方法.我不希望它只是处理异常,它将记录异常,然后调用另一个返回值与getValue()类型相同的方法.

pam*_*amu 6

使用recoverrecoverWith

当future将来因异常而失败时,将调用recover或recoverWith.在恢复块中,您可以提供替代值.

recoverWith不同于recover未来的东西

getValue().recover { case th =>
  //based on the exception type do something here
  defaultValue //returning some default value on failure
}
Run Code Online (Sandbox Code Playgroud)


ann*_*iid 3

我最终做的是使用 Future.fallbackTo() 方法。

def method(): Future[JsObject] = {
    getValue().fallbackTo(method1()).fallbackTo(method2()).fallbackTo(method3())
}
Run Code Online (Sandbox Code Playgroud)

如果 future 从一开始就getValue()失败,它将调用method1()。如果也失败,它将调用method2()etc。如果其中一个方法成功,它将返回该值。如果没有一个方法成功,它将返回失败的 future getValue()

这个解决方案并不理想,因为我希望包含所有尝试失败时抛出的所有四个异常,但它至少允许我重试该getValue()方法。