【问题标题】:Cannot catch ConnectionError with requests无法通过请求捕获 ConnectionError
【发布时间】:2016-12-06 08:01:10
【问题描述】:

我正在这样做:

import requests
r = requests.get("http://non-existent-domain.test")

得到

ConnectionError: HTTPConnectionPool(host='non-existent-domain.test', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x10b0170f0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))

但是,如果我尝试像这样抓住它:

try:
    r = requests.get("http://non-existent-domain.test")
except ConnectionError:
    print("ConnectionError")

没有任何变化,我仍然有 ConnectionError 未处理。如何正确捕捉?

【问题讨论】:

    标签: python exception-handling python-requests


    【解决方案1】:

    这是一个不同的ConnectionError。你正在赶上内置的,但requests 有它自己的。所以这应该是

    try:
        r = requests.get("http://non-existent-domain.test")
    except requests.ConnectionError:
        print("ConnectionError")
    
    # Output: ConnectionError
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 2013-10-22
      • 1970-01-01
      • 2021-12-27
      相关资源
      最近更新 更多