处理 SheetsAPI 错误 - Python 2.7

Handling SheetsAPI errors - Python 2.7

很需要你的帮助,我一直在努力解决这个问题,并尝试了 urllib2 和其他人来尝试捕获加载不存在的 sheet.

时给出的 HttpError

所以这是初始调用代码

discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?''version=v4')
service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl)
result = service.spreadsheets().values().get(spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values', [])

if not values:
     print('No data found.')
     tkMessageBox.showwarning("ERROR", "There is nothing on this page!")
     LoadCSV()
else:

好的,现在就这样。当我调用不存在的 sheet 时,我想处理错误并显示一条警告 "No more sheets to try"

这是错误:

HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/(ID)/values/130%21A2%3AI?alt=json returned "Unable to parse range: 130!A2:I">

如何处理此错误以发出该页面不存在的警告并终止程序。

我在使用 sheets-api-quickstart 时看到 googleapiclient.errors.HttpError。这对我有用:

import googleapiclient

discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?''version=v4')
service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl)
try: 
     # The `execute()` call triggers the exception.
     result = service.spreadsheets().values().get(spreadsheetId=spreadsheetId, range=rangeName).execute()
     # deceptively named, custom HttpError
except googleapiclient.errors.HttpError:
     print "page does not exist"
else:
    values = result.get('values', [])

    if not values:
         print('No data found.')
         tkMessageBox.showwarning("ERROR", "There is nothing on this page!")
         LoadCSV()
    else: