我刚开始学习期货,偶然发现了一个对我来说很奇怪的错误:
使用play-ws执行post请求并映射结果:
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]]]
不匹配
基于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 WSn" + debugResponse(response))
Future.failed(new RuntimeException("ws-error"))
}
}