I am using gspread module to read stuff from a Google Sheet using Python. Sometimes, I hit an error which I can trace from the Python console.
But I would like my Python code to handle it, and tell me as much details as possible about what is causing the error. I suppose this should be done using try/catch, but I couldn't find any examples to understand...
- how to get info from gspread about the gspread error details, and
- how to handle it into a dictionary so I can print out the error myself.
import gspread
try:
# do some stuff
except gspread.exceptions.APIError as e:
print("ERROR", e, type(e))
# what should I put in the previous lines to handle the exception
# and get the error details into a python variable, i.e. err
# print("Error {}: {}".format(err['code'], err['name']))
# print(" (raised by {} line {})".format(err['script'], err['line']))
current output (for example if I try to access a file which is not mine):
ERROR {
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "File not found: 1eIjkFBQmTo2TCr7hf4HFItSsBQmGAT-t3ZXH1LlEmNk",
"locationType": "other",
"location": "file"
}
],
"code": 404,
"message": "File not found: 1eIjkFBQmTo2TCr7hf4HFItSsBQmGAT-t3ZXH1LlEmNk"
}
}
<class 'gspread.exceptions.APIError'>
My main concern is getting error code and error name/description into a variable (dictionary, list or whatever ... I don't care).
But if I could also get the script & line of my code which raised the error, that would be great.