我正在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(抛出Errors.AUTH_CANCEL)和PurePromise(抛出Errors.BAD_RESPONSE)。我对解决方案的尝试正确地处理了成功,但在我得到的例外情况上:
play.api.Application$$anon$1: Execution exception[[AUTH_CANCEL$: null]]
我的问题是如何在我的控制器方法中捕获并处理这些异常?
答案 0 :(得分:10)
您应该使用recover
Future
方法而不是Try
这样的方法:
Async (
OpenID.verifiedId.
map{userInfo => Ok(userInfo.id + "\n" + userInfo.attributes)}.
recover{ case thrown => Ok("failed: " + thrown) }
)
Try
可以帮助您verifiedId
抛出异常而不是返回Future
。在您的情况下,verifiedId
成功返回Future
(即使此Future
中存在例外情况)。