当 googleapiclient 构建失败时捕获 401 错误?

Catching 401 error when a googleapiclient build fails?

我目前正在尝试捕捉一个边缘案例,当用户在我们不知情的情况下将我的应用程序作为第三方应用程序删除时。我目前不知道 google 有什么方法可以让我知道令牌是否已被撤销,直到我收到 google.auth.exceptions.RefreshError: ('invalid_grant: Token has been expired or revoked.', '{\n "error": "invalid_grant",\n "error_description": "Token has been expired or revoked."\n}')

我在授权用户之前手动尝试 'pinging' google 客户端,但它似乎比仅在错误发生时捕获和处理错误慢一点。我也试过直接导入 auth 错误。 import google.auth.exceptions.RefreshError as AuthError

正在检索凭据:

storage = Storage(GCalUser, 'gcal_user', request.user, 'credentials')
user_credentials = storage.get()

实际调用:

try:
    calendar_service = googleapiclient.discovery.build('calendar', 'v3', credentials=user_credentials)
    print("Error 2: " + str(calendar_service))
except calendar_service:
    pass

正在寻找在身份验证出错时将用户定向到其他页面的方法。目前它只是失败 google.auth.exceptions.RefreshError: ('invalid_grant: Token has been expired or revoked.', '{\n "error": "invalid_grant",\n "error_description": "Token has been expired or revoked."\n}')

修复了从模块 from google.auth.exceptions import RefreshError 显式完全导入错误的问题。事实证明,错误不是在使用用户凭据构建时引发的,而是在使用 api.

执行时引发的
try:
    calendar_list = calendar_service.calendarList().list(pageToken=page_token, minAccessRole="writer").execute()
except RefreshError:
    print("Hello debugging!")