scala - Play Framework 异步操作 : Future recover not working

标签 scala asynchronous playframework future

我的 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/

相关文章:

scala - Spark 中的展平行

javascript - Node.js 在函数之间异步传递变量

java - 如何设置路由来连接将用户定义的类数组作为 playframwork 2.1 中的输入的函数?

scala - 在元组中拆分字符串

java - 使用 Spark 连接 MariaDB 时出现 ClassNotFoundException

c# - Task.ContinueWith 是否捕获调用线程上下文以继续?

playframework - Play 框架 - 在 Scala 模板中使用 Javascript 变量

mysql - 表情符号插入 Play Framework

java - scala 模式匹配

.NET 异步套接字与后台 worker