如何从EssentialAction中的Future中恢复错误

时间:2015-06-03 18:51:48

标签: scala playframework future iterate

this帖子的示例开始,我想知道如何处理recover

def HasToken(action: String => EssentialAction): EssentialAction = EssentialAction { requestHeader =>
  val maybeToken = requestHeader.headers.get("session")

  val futureIteratee: Future[Iteratee[Array[Byte], SimpleResult]] = maybeToken map { token =>
    //This returns a future...
    Session.find(token).map {
      case Some(session) => action(session)(requestHeader)
      case None => Done[Array[Byte], Result](Unauthorized("Invalid token"))
    }.recover {
      Done[Array[Byte], Result](Unauthorized("400 Error finding Security Token\n"))
    }
  } getOrElse {
    Future.successful(Done[Array[Byte], Result](Unauthorized("401 No Security Token\n")))
  }

  Iteratee.flatten(futureIteratee)
}

上面的代码无法编译,我总是收到以下错误消息:

[error] /home/j3d/projects/test/app/Security.scala:80: type mismatch;
[error]  found   : scala.concurrent.Future[play.api.libs.iteratee.Iteratee[_4,play.api.mvc.Result] forSome { type _4 >: _3 <: Array[Byte]; type _3 <: Array[Byte] }]
[error]  required: scala.concurrent.Future[play.api.libs.iteratee.Iteratee[Array[Byte],play.api.mvc.Result]]
[error]         } recover {
[error]           ^
[error] one error found
[error] (compile:compile) Compilation failed

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

奇怪的是,我认为问题可能是因为该功能并没有推断出你需要的正确类型。过去发生过这种情况,结果类型依赖于现有的泛型类型,例如: U >: T

尝试完你的代码片段之后,我注意到你没有使用部分函数进行recover调用,并在我修复它编译后没有任何问题。

Session.find(token).map {
    case Some(session) => action(session)(requestHeader)
    case None => Done[Array[Byte], Result](Unauthorized("Invalid token"))
}.recover {
    case _ =>
        Done[Array[Byte], Result](Unauthorized("400 Error finding Security Token\n"))
}