如果未来返回失败的异常,我该如何处理?
场景是,我的代码调用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)
}
}
更新:我认为我在最初的问题中没有明确说明这一点,但我平面映射值的原因是,我不想明确地等待代码中的任何未来,因此我不想使用Future.onComplete{}来解析值。
更新2:另一件可能不清楚的事情是,如果它抛出异常,我想调用另一个方法。我不希望它只处理异常,它将记录异常,然后调用另一个返回值与getValue((类型相同的方法。
使用recover
或recoverWith
recover或recoverWith在future出现异常而失败时调用。在恢复块中,您可以给出替代值。
recoverWith
不同于recover
,它是的未来
getValue().recover { case th =>
//based on the exception type do something here
defaultValue //returning some default value on failure
}
我最终使用的是Future.fallbackTo((方法。
def method(): Future[JsObject] = {
getValue().fallbackTo(method1()).fallbackTo(method2()).fallbackTo(method3())
}
如果来自第一个getValue()
的future失败,它将调用method1()
。如果同样失败,它将调用method2()
等。如果其中一个方法成功,它将返回该值。如果没有一个方法成功,它将从getValue()
返回失败的future。
这种解决方案并不理想,因为如果所有尝试都失败,我最好将抛出的所有四个异常都包括在内,但它至少允许我重试getValue()
方法。
import scala.util.{Success, Failure}
f.onComplete {
case Success(value) => // do sth with value
case Failure(error) => // do sth with error
}
你可以在你的方法((中使用onComplete,其他选项也可以参见下面的链接:
http://www.scala-lang.org/api/2.9.3/scala/concurrent/Future.html