5

我正在 play 框架中编写一个控制器方法,该方法调用一个函数,该函数返回一个也可能引发异常的 Future。我无法弄清楚如何捕获和处理该异常。

这是我尝试过的:

  def openIDCallback = Action { implicit request =>
    Async (
      Try(OpenID.verifiedId) match {
        case Failure(thrown) => {
          PurePromise(Ok("failed: " + thrown))
        }
        case Success(successResult) => {
          successResult.map( userInfo => {
            Ok(userInfo.id + "\n" + userInfo.attributes)
          })
        }
      }
    )
  }

OpenID.verifiedId 是 Play 的 OpenId api 中返回 Future[UserInfo] 的函数。这是该功能的来源:

def verifiedId(queryString: Map[String, Seq[String]]): Future[UserInfo] = {
    (queryString.get("openid.mode").flatMap(_.headOption),
      queryString.get("openid.claimed_id").flatMap(_.headOption)) match { // The Claimed Identifier. "openid.claimed_id" and "openid.identity" SHALL be either both present or both absent.
      case (Some("id_res"), Some(id)) => {
        // MUST perform discovery on the claimedId to resolve the op_endpoint.
        val server: Future[OpenIDServer] = discovery.discoverServer(id)
        server.flatMap(directVerification(queryString))(internalContext)
      }
      case (Some("cancel"), _) => PurePromise(throw Errors.AUTH_CANCEL)
      case _ => PurePromise(throw Errors.BAD_RESPONSE)
    }
  }

如上所示,函数可以返回 PurePromise(throw Errors.AUTH_CANCEL) 和 PurePromise(throw Errors.BAD_RESPONSE)。我对解决方案的尝试正确处理了成功,但在异常情况下我得到:

play.api.Application$$anon$1: Execution exception[[AUTH_CANCEL$: null]]

我的问题是如何在我的控制器方法中捕获和处理这些异常?

4

1 回答 1

10

您应该使用recover方法Future而不是Try这样:

Async (
  OpenID.verifiedId.
    map{userInfo => Ok(userInfo.id + "\n" + userInfo.attributes)}.
    recover{ case thrown => Ok("failed: " + thrown) }
)

TryverifiedId如果抛出异常而不是返回,可以帮助您Future。在您的情况下verifiedId成功返回Future(即使 this 会有异常Future)。

于 2013-09-29T12:53:18.633 回答