Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling SheetsAPI errors - Python 2.7

need your help big time, i've been trying to figure this out and have tried urllib2 and others to try capturing the HttpError given when loading a non-existent sheet.

So here is the initial calling code

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:

Okay so now. When I call a sheet which doesn't exist I want to handle the error and show a warning saying "No more sheets to try"

Here is the error:

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">

How can I handle this error to instead give a warning that the page doesn't exist and to terminate the program.

like image 241
Joel Avatar asked Jul 04 '26 17:07

Joel


1 Answers

I see a googleapiclient.errors.HttpError when I use the sheets-api-quickstart. This works for me:

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:
like image 72
Elliott Beach Avatar answered Jul 07 '26 06:07

Elliott Beach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!