按照DartWatch blog上的教程使用Google OAuth库。问题是如何处理:来自Google的“拒绝访问”错误?
这是我的代码示例:
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
块。我做错了什么?我正在使用:
Dart编辑器版本0.5.0_r21823
Dart SDK版本0.5.0.1_r21823
最佳答案
您永远不会碰到catch块,因为auth.login
是一个返回Future的异步操作。
有一个great article on Future error handling on the dartlang.org
website。auth.login
returns 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.
}
}
关于dart - google_oauth2_client如何处理 'Access denied',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16195136/