【问题标题】:Get Errno from Python Requests ConnectionError?从 Python 请求 ConnectionError 中获取 Errno?
【发布时间】:2013-10-22 14:53:51
【问题描述】:

我正在捕获并打印 Python Requests ConnectionErrors 很好:

except requests.exceptions.ConnectionError as e:
    logger.warning(str(e.message))

它打印出如下消息:

HTTPSConnectionPool(host='10.100.24.16', port=443): Max retries exceeded with url: /api/datastores/06651841-bbdb-472a-bde2-689d8cb8da19 (Caused by <class 'socket.error'>: [Errno 61] Connection refused)

HTTPSConnectionPool(host='10.100.24.16', port=443): Max retries exceeded with url: /api/datastores/06651841-bbdb-472a-bde2-689d8cb8da19 (Caused by <class 'socket.error'>: [Errno 65] No route to host)

还有很多其他的。我想知道的是,获取消息中显示的 errno 的最佳、最 Pythonic 的方法是什么?我希望有一个可靠的系统来捕获问题并尽可能向用户提供有用且相关的错误消息。据我所知,ConnectionError 是 BaseException 的间接继承者,除了 BaseException 提供的之外,没有添加任何新属性或方法。我对简单地使用正则表达式犹豫不决,因为在我看来,我冒着假设所有错误消息在所有地方的格式都相同的风险。

【问题讨论】:

    标签: python python-2.7 exception-handling python-requests errno


    【解决方案1】:

    我认为您可以使用e.args[0].reason.errno 访问它。

    这可能在某处有记录,但通常当我必须追查这样的事情时,我只是在控制台上尝试并挖掘一下。 (我使用 IPython,所以很容易进行 tab-inspection,但让我们尝试一下)。

    首先,让我们生成一个错误

    import requests
    try:
        requests.get("http://not.a.real.url/really_not")
    except requests.exceptions.ConnectionError as e:
        pass
    

    这应该会给我们e中的错误:

    >>> e
    ConnectionError(MaxRetryError("HTTPConnectionPool(host='not.a.real.url', port=80): Max retries exceeded with url: /really_not (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)",),)
    

    信息通常在args:

    >>> e.args
    (MaxRetryError("HTTPConnectionPool(host='not.a.real.url', port=80): Max retries exceeded with url: /really_not (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)",),)
    >>> e.args[0]
    MaxRetryError("HTTPConnectionPool(host='not.a.real.url', port=80): Max retries exceeded with url: /really_not (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)",)
    

    往里看,我们看到:

    >>> dir(e.args[0])
    ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',
     '__getitem__', '__getslice__', '__hash__', '__init__', '__module__', '__new__',
     '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__',
     '__str__', '__subclasshook__', '__unicode__', '__weakref__', 'args', 'message', 'pool',
     'reason', 'url']
    

    reason 看起来令人鼓舞:

    >>> e.args[0].reason
    gaierror(-2, 'Name or service not known')
    >>> dir(e.args[0].reason)
    ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',
     '__getitem__', '__getslice__', '__hash__', '__init__', '__module__', '__new__',
     '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__',
     '__str__', '__subclasshook__', '__unicode__', '__weakref__', 'args', 'errno', 'filename',
     'message', 'strerror']
    >>> e.args[0].reason.errno
    -2
    

    【讨论】:

    • +1:做得很好!非常感谢!我已经到了 dir(e) 和 e.args,但我已经停止了,我将 e.args 的元素误认为是我必须使用正则表达式来提取我想要的信息的字符串。跨度>
    • 使用虚假 URL 也是产生错误的好方法。我一直在使用真实的 URL,但我的互联网被关闭了......在生成错误和研究它们之间来回切换很不方便。
    • 天哪 - 谢谢谢谢 - 这个错误让我很生气!
    • 在 Python 3.8.5 中,我在 e.errnoe.args[0] 中得到 errno; e.strerrore.args[1] 中的原因短信。
    【解决方案2】:

    我在使用 python 3.6 和 requests 2.18 获得相同结果时遇到了麻烦。我设法使用httpsocket 模块获取errno:

    import socket, html
    try:
        http.client.HTTPConnection('invalid').connect()
    except (socket.gaierror, ConnectionError) as e:
        print(e.errno)
    

    希望它可以帮助别人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多