【问题标题】:Scala: failing a Future based on a Future#collectScala:基于 Future#collect 失败的 Future
【发布时间】:2016-05-09 14:24:31
【问题描述】:

WS.post 返回一个Future[Response],但我想要一个Future[Data],所以我为此目的使用Future.collect

private def getDataFuture(data: String): Future[JsValue] =
    initAuthenticatedRequest().post(body).collect {
    case response => response.json(0)
  }.recoverWith {
    case NonFatal(_) => getDataFuture(data)
  }

但是,有时response.json(0) 会返回一个错误的值,因为我收到一个空的 json。我预计这会导致 Future 失败并执行recoverWith,但这并没有发生。

我需要在收集案例中进行分支吗? 我怎样才能更优雅地处理这个问题?我想 Future 会对此有所规定。

【问题讨论】:

  • 调试器显示 'JsUndefined({} is not an array' for the value
  • val r: Future[JsValue] = WS.url("").post[String]("").map(response => response.json)。为什么你使用response.json(0)。 Сan你更好地描述问题(响应示例以及你最后需要什么)
  • response.json(0) 引用 json 数组中的第一个元素,但有时由于已知错误,服务器会发送空 json
  • 使用recoverWith 的重要注意事项 - 如果服务器无法访问,可能会因为递归调用而导致无限循环和堆栈溢出。
  • 我不知道你想要如何使用结果,但无论如何阻塞都不好。

标签: scala playframework playframework-2.0 future


【解决方案1】:

你必须使用

initAuthenticatedRequest().post(body).map(_.json.as[JsArray])

json.as[JsArray]将json转换为JsArray或者抛出异常,可以用recoverWith处理

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 1970-01-01
    • 2019-10-25
    • 2014-01-19
    • 2023-03-20
    • 2015-07-30
    • 2016-11-08
    • 2016-05-04
    相关资源
    最近更新 更多