使用 Requests 库打印错误

Printing out errors with Requests library

我一直在通读 http://www.mobify.com/blog/http-requests-are-hard/ ,其中讨论了请求可能遇到的各种类型的错误。本文着重于捕捉每一个。我想在发生任何错误时简单地打印出错误类型。在文章中,一个例子是:

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

有没有办法将伪代码中的最后两行重写为:

except requests.ANYERROR as e:
    print e

来自my other answer

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

所以这应该捕获所有内容:

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

所有请求异常都继承自 requests.exceptions.RequestException,因此您可以:

try:
    ....
    ....
except requests.exceptions.RequestException as e:
    # Do whatever you want to e
    pass