pythonerror-handlingpython-requests

Printing out errors with Requests library


http://www.mobify.com/blog/http-requests-are-hard/ discusses various types of errors which can be encountered with a request. The article focuses on catching each one. I would like to simply print out the error type whenever any error occurs. In the article, one example is:

url = "http://www.definitivelydoesnotexist.com/"

try:
    response = request.get(url)
except requests.exceptions.ConnectionError as e:
    print "These aren't the domains we're looking for."

Is there a way to rewrite the last 2 lines in pseudocode as:

except requests.ANYERROR as e:
    print e

Solution

  • From my other answer:

    All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

    So this should catch everything:

    try:
        response = requests.get(url)
    except requests.exceptions.RequestException as e:
        print e