2013-02-11 75 views
0

使用播放框架2.1的OpenID,如果我從OpenID提供者取消我認證,我得到這個異常:

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

這裏是我的代碼:

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

但因爲它是一個運行時異常,我不能用try/catch來捕獲它,所以我被困在如何避免異常,並返回比服務器錯誤更好的東西給客戶端。

我該怎麼辦?

感謝您的幫助!

回答

1

承諾是成功的偏見,對於所有的操作,它假定它實際上包含一個值而不是一個錯誤。 由於您試圖對包含未轉換錯誤的承諾調用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(); 
     } 
    } 
} 
+0

尼斯的答案,我想測試它,但我的代碼是在Java中:/你能提供的Java代碼替代,這將是偉大的! :) – 2013-02-18 07:05:34

+0

謝謝你的更新! :) – 2013-02-18 15:17:03