【发布时间】:2017-10-04 21:17:09
【问题描述】:
我正在使用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,但我看不到明显的方法。
如果出现不同的Future 失败案例,我如何调用不同的http4s 任务包装器?我需要使用中间件吗?
【问题讨论】: