Scala未来完成奇怪的错误

时间:2016-05-10 22:10:07

标签: scala playframework future

我刚开始接触期货,偶然发现了一个对我来说很奇怪的错误:

使用play-ws执行发布请求并映射结果:

wsClient.url(url).withHeaders("Content-Type" -> "application/json")
      .post(payload)
      .map { wsResponse =>
        if (!(200 to 299).contains(wsResponse.status)) {
          sys.error(s"Received unexpected status, open-cpu error ${wsResponse.status} : ${wsResponse.body}")
        }
        println(s"OK, received ${wsResponse.body}")

        wsResponse.json.validate[Seq[MyClass]] match {
          case JsSuccess(result, _) => result.map(outlierRes => Map("key" -> outlierRes.attr, "key2" -> outlierRes.attr2, "key3" -> outlierRes.val3))
          case JsError(error) => throw new MyException(error.toString())
        }
      }

工作得很好。身体的println显示一切都在那里,验证成功。

问题在于:aggregatedData = Await.result(theFutureFromAbove, 20.minutes)

通过交互式控制台运行时,此语句与以下内容发生冲突:

MyException
        at $anonfun$1.apply(<console>:44)
        at $anonfun$1.apply(<console>:44)
        at scala.util.Success$$anonfun$map$1.apply(Try.scala:206)
        at scala.util.Try$.apply(Try.scala:161)
        at scala.util.Success.map(Try.scala:206)
        at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:235)
        at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:235)
        at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
        at scala.concurrent.impl.ExecutionContextImpl$$anon$3.exec(ExecutionContextImpl.scala:107)
        at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
        at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
        at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
        at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

这会建议解析异常。

但是,当通过sbt run运行时,会有一个不同的例外:

java.lang.NullPointerException

类似于这一行:wsClient.url(baseUrl + url).withHeaders("Content-Type" -> "application/json")

修改

似乎是由wsClient.close()触发,好像我在未来完成之前关闭了wsClient。 但是,在文档中说明了

  

如果手动创建WSClient,则必须调用client.close()   完成后清理它。

那我应该把它关在哪里?最初,我认为在Await.result之后关闭是安全的,但仍然会抛出错误。

编辑2

wsResponse.json.validate[Seq[MyClass]].fold(
          error => {
            println(error)
            Future.failed(new MyException("parsing failed" + error))
          },
          result => result.map(data => Map("period" -> data.period, "amount" -> data.totalAmount, "outlier" -> data.isOutlier))
        )

但由于Future[nothing]Future[Seq[Map[String, Any]]]

的返回类型不匹配,因此仍无法编译

1 个答案:

答案 0 :(得分:0)

基于https://github.com/studiodev/Mocky/blob/master/app/services/GithubRepository.scala我终于找到了与

类似的东西
private def parseGistResponse(response: WSResponse): Future[GistResponse] = {
    if (response.status < 400) {
      logger.debug(s"<< (${response.status}) ${response.body}")
      response.json.validate[GistResponse].fold(
        error => {
          logger.error(s"Unable to parse GistResponse: $error")
          Future.failed(new RuntimeException("parse-json-failed"))
        },
        gistResponse => Future.successful(gistResponse))
    } else {
      logger.error("Unable to parse GitResponse, cannot contact WS\n" + debugResponse(response))
      Future.failed(new RuntimeException("ws-error"))
    }
  }