2013-04-24 57 views
2

關於使用Google OAuth庫的教程DartWatch blog。問題是如何處理:來自Google的「拒絕訪問」錯誤?google_oauth2_client如何處理「訪問被拒絕」

這裏是我的代碼示例:

class Client 
{ 

    GoogleOAuth2 _auth; 

    Client() 
    { 
     _auth = new GoogleOAuth2(
         '5xxxxxxxxxxxxxx.apps.googleusercontent.com', // Client ID 
         ['openid', 'email', 'profile'], 
         tokenLoaded:oauthReady); 
    } 

    void doLogin() 
    { 
     // _auth.logout(); 
     // _auth.token = null; 
     try 
     { 
      _auth.login(); 
     } 
     on AuthException { 
      print('Access denied'); 
     } 
     on Exception catch(exp) 
     { 
      print('Exception $exp occurred'); 
     } 
    } 

    void oauthReady(Token token) 
    { 
     print('Token is: $token'); 
    }   
} 

,但我從不打catch塊任何異常(!)。我做錯了什麼?

我使用:
飛鏢編輯器版本0.5.0_r21823
飛鏢SDK版本0.5.0.1_r21823

回答

1

你從不打catch塊,因爲auth.login是一個異步操作,它返回一個Future 。

有一個great article on Future error handling on the dartlang.org website

auth.loginreturns a Future立即,但是控制返回到事件循環之後它的工作情況

你的代碼應該看起來更像(見my answer to another question更多關於事件循環。):

/// Returns a Future that completes to whether the login was successful. 
Future<boolean> doLogin() 
{ 
    _auth.login() 
    .then((_) { 
     print("Success!"); 
     return true; 
    }.catchError((e) { 
     print('Exception $e occurred.'); 
     return false; // or throw the exception again. 
    } 
} 
+0

謝謝:)我忘了'_auth.Login()'是一個'Future' – Jasper 2013-04-25 06:55:57