我使用的是http4s,我有一个Try,它为响应生成一些json数据:
case GET -> Root / "something" =>
getSomethingTry() match {
case Success(something) => Ok(something)
case Failure(CustomNotFoundException(reason)) => NotFound(reason)
case Failure(CustomConflictException()) => Conflict()
}此函数正确地返回一个Task[Response]
但是,我想用一个Try替换Future。匹配不再有效,因为在比赛时,未来可能还没有解决。所以,我可以描绘未来:
case GET -> Root / "something" =>
getSomethingFuture().map {
something => Ok(something)
}.recover {
case CustomNotFoundException(reason) => NotFound(reason)
case CustomConflictException() => Conflict()
}但是这会返回一个Future[Task[Response]],这不是http4s想要的。使用Await.result来解压缩Future似乎不合适--我认为这可能会导致线程池问题--但它确实使代码正常工作。
http4s接受期货作为任务创建者的参数:
case GET -> Root / "something" =>
Ok(getSomethingFuture())但这不允许我在发生不同错误时设置不同的状态代码。解决方案可能是在任务上执行.recover,但我看不出有什么明显的方法。
在不同的http4s失败案例中,我如何调用不同的Future任务包装器?我需要使用中间件吗?
发布于 2017-10-04 11:52:53
假设您使用的是http4s 0.17和更高版本,那么您的Task就是fs2.Task。
很容易将Future转换为Task,然后处理后者:
case GET -> Root / "something" =>
Task.fromFuture(getSomethingFuture())
.flatMap {
something => Ok(something)
}
.handleWith {
case CustomNotFoundException(reason) => NotFound(reason)
case CustomConflictException() => Conflict()
}不过,我建议您在整个程序中使用Task,而不是Try或Future
发布于 2017-10-04 13:17:09
你真的不需要打开未来。Play框架为返回未来提供了action.async。
您可以通过以下方式使用它
Action.async {
getSomethingFuture().map {
something => Ok(something)
}.recover {
case CustomNotFoundException(reason) => NotFound(reason)
case CustomConflictException() => Conflict()
}
}https://www.playframework.com/documentation/2.6.x/ScalaAsync#returning-futures
https://stackoverflow.com/questions/46555319
复制相似问题