简体   繁体   中英

Python: Handling requests exceptions the right way

I recently switched from urlib2 to requests and I'm not sure how to deal with exceptions. What is best practice? My current code looks like this, but is not doing any good:

try:
    response = requests.get(url)
except requests.ConnectionError , e:
    logging.error('ConnectionError = ' + str(e.code))
    return False
except requests.HTTPError , e:
    logging.error('HTTPError = ' + str(e.reason))
    return False
except requests.Timeout, e:
    logging.error('Timeout')
    return False
except requests.TooManyRedirects:
    logging.error('TooManyRedirects')
    return False
except Exception:
    import traceback
    logging.error('generic exception: ' + traceback.format_exc())
    return False

Since it looks bad as a comment, have you tried:

try:
    # some code
except Exception as e:
    print e

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