简体   繁体   中英

how to implement try-catch and get the name and code of the gspread error

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.

It seems that all gspread error information was being returned as a json string, so my problem was knowing how to parse it to access its elements:

import gspread
try:
    # do some stuff
except gspread.exceptions.APIError as e:
    import json,os
    ej = json.loads(str(e))["error"]
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    err = {'code':ej['code'], 'message':ej['message'],'script':fname, 'line':exc_tb.tb_lineno}
    print("Error {}: {}".format(err['code'], err['message']))
    print(" (raised by {} line {})".format(err['script'], err['line']))

Thanks @Tomerikoo for the link about file and line information .

That was it !

Hopefully @Burnash ( gspread developer) can tell us if there is a more direct way to get error codes & messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM