0

使用带有 OpenID 的 Play Framework 2.1,如果我从 OpenID 提供者取消我的身份验证,我会收到以下异常:

[RuntimeException: play.api.libs.openid.Errors$AUTH_CANCEL$]

这是我的代码:

Promise<UserInfo> userInfoPromise = OpenID.verifiedId();
UserInfo userInfo = userInfoPromise.get(); // Exception thrown here

但由于它是一个运行时异常,我无法用 try/catch 捕获它,所以我坚持如何避免异常并向客户端返回比服务器错误更好的东西。

我怎样才能做到这一点?

4

1 回答 1

1

Promise 是偏向成功的,对于它的所有操作,它假设它实际上包含一个值而不是一个错误。您收到异常是因为您尝试调用get包含未转换错误的承诺。

您想要确定 Promise 是成功还是错误,例如,您可以通过模式匹配来做到这一点。

试试这个代码:

AsyncResult(
      OpenID.verifiedId.extend1( _ match {
        case Redeemed(info) => Ok(info.attributes.get("email").getOrElse("no email in valid response"))
        case Thrown(throwable) => {
          Logger.error("openid callback error",throwable)
          Unauthorized
        }
      }
      )
    )

您可能想阅读更多关于未来和承诺的信息,我推荐这篇优秀的文章: http ://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to -the-future.html

编辑:检查java中的文档(http://www.playframework.com/documentation/2.1.0/JavaOpenID)似乎你应该自己捕捉和处理异常。

在任何情况下,您都应该捕获异常,如果抛出异常,则将用户重定向回包含相关信息的登录页面。

像这样的东西应该可以工作:

public class Application extends Controller {


    public static Result index() {
        return ok("welcome");
    }

    public static Result auth() {
        Map<String, String> attributes = new HashMap<String, String>();
        attributes.put("email", "http://schema.openid.net/contact/email");
        final Promise<String> stringPromise = OpenID.redirectURL("https://www.google.com/accounts/o8/id", "http://localhost:9000/auth/callback",attributes);
        return redirect(stringPromise.get());
    }


    public static Result callback() {
        try{
            Promise<UserInfo> userInfoPromise = OpenID.verifiedId();
            final UserInfo userInfo = userInfoPromise.get();
            System.out.println("id:"+userInfo.id);
            System.out.println("email:"+userInfo.attributes.get("email"));
            return ok(userInfo.attributes.toString());
        } catch (Throwable e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
            return unauthorized();
        }
    }
}
于 2013-02-17T21:21:22.117 回答