使用请求库打印出错误

时间:2015-06-22 22:18:27

标签: python python-requests

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

selectAll = function (event) {
        var self = this;
        $('.template-item-select').each(function () {
            this.checked = self.checked;
        });
    }

有没有办法用伪代码重写最后2行:

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

2 个答案:

答案 0 :(得分:2)

来自my other answer

  

请求明确提出的所有异常都来自 requests.exceptions.RequestException

所以这应该抓住一切:

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

答案 1 :(得分:1)

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

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