【问题标题】:Dealing with failed futures处理失败的期货
【发布时间】:2014-06-30 21:37:38
【问题描述】:

在 Play Framework 2.3 中,操作可以从成功的未来调用中产生结果,如下所示:

def index = Action.async {
  val futureInt = scala.concurrent.Future { intensiveComputation() }
  futureInt.map(i => Ok("Got result: " + i))
}

但是操作如何处理失败的未来调用,即通过调用failure() 而不是success() 完成的未来?

例如,一个动作如何产生一个InternalServerError 结果,并在未来的失败可抛出中返回消息?

onCompleteonFailure 回调似乎不适合操作流程(它需要返回一个结果,无论是来自成功的未来还是失败的未来)。

【问题讨论】:

    标签: playframework future playframework-2.3


    【解决方案1】:

    对于单个Action,您可以使用recover 执行此操作,将失败的Future 恢复为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 来实现这一点。

    【讨论】:

      猜你喜欢
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 2017-09-30
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      相关资源
      最近更新 更多