我的 play 2 应用程序中有以下代码:
Controller :
...
def getUserById(id: Long) = Action.async {
try {
userService.findById(id)
.map(u => Ok(Json.toJson(u))
.recover {
case e: Exception => Ok("Exception got")
}
}
}
...
服务:
...
override def findAll: Future[Seq[User]] = {
throw new Exception("Error 1")
}
...
但是在 Controller 中,我无法捕获服务中抛出的异常(以某种方式忽略了恢复块)。相反,显示带有异常“错误 1”的 Play 标准错误页面。
我究竟做错了什么?
最佳答案
您的代码在返回 Future
之前抛出异常,所以你应该:
override def findAll: Future[Seq[User]] = Future {
throw new Exception("Error 1")
}
要不就:
override def findAll: Future[Seq[User]] =
Future.failed(new Exception("Error 1"))
这样 - 异常将被包裹在
Future
中的实例,因此每个订阅者都可以异步获取它并通过 recover
处理.否则,您必须通过用 try{ findAll(...) } catch {...}
包装它来同步处理失败。 .附言抛出异常 is not referentially transparent ,这就是为什么有时很难理解这种行为的原因。将错误包装到
Future
中的方法更纯粹,所以我更愿意让代码更清晰。
关于scala - Play Framework 异步操作 : Future recover not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38556452/