处理失败的期货 [英] Dealing with failed futures
问题描述
在Play Framework 2.3中,操作可以从成功的将来调用中产生结果,如下所示:
In Play Framework 2.3, an action can produce a result from a successful future call like this:
def index = Action.async {
val futureInt = scala.concurrent.Future { intensiveComputation() }
futureInt.map(i => Ok("Got result: " + i))
}
但是,动作如何处理失败的将来调用,即通过调用failure()
而不是success()
完成的将来?
But how can an action deal with a failed future call, i.e., a future that was completed by calling failure()
instead of success()
?
例如,一个动作如何产生InternalServerError
结果,并在将来的故障的throwable中返回消息?
For instance, how could an action produce a InternalServerError
result with the message returned in the future's failure's throwable?
onComplete
和onFailure
回调似乎与操作流程不符(它需要从成功的未来或失败的未来返回结果).
onComplete
and onFailure
callbacks don't seem to fit the action's flow (it needs to return a result, either from a successful future or a failed one).
推荐答案
对于单个Action
,您可以使用recover
执行此操作,将失败的Future
恢复到Result
:
For a single Action
, you can do this with recover
, recovering the failed Future
to a Result
:
def index = Action.async {
val futureInt = scala.concurrent.Future { intensiveComputation() }
futureInt.map(i => Ok("Got result: " + i))
.recover{ case e: Exception => InternalServerError(e.getMessage) }
}
在这种情况下,
recover
是PartialFunction[Throwable, Result]
,因此您可以更加精细地进行错误处理,并且PartialFunction
中未定义的任何内容都将是失败的Future
.更一般而言,您可能会使用实现此目的的自定义定义的Action
.
recover
in this case is a PartialFunction[Throwable, Result]
, so you can be more fine grained with your error handling, and anything that is not defined in the PartialFunction
will remain a failed Future
. More generally, you could probably use a custom defined Action
that implements this.
这篇关于处理失败的期货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!