gpt4 book ai didi

python - 从 Python 请求 ConnectionError 获取 Errno?

转载 作者:太空狗 更新时间:2023-10-29 19:32:44 24 4
gpt4 key购买 nike

我正在捕获并打印 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 提供的新属性或方法。我对简单地使用正则表达式犹豫不决,因为在我看来,我冒着假设所有错误消息在所有地方都采用相同格式的风险。

最佳答案

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

这可能记录在某处,但通常当我必须追踪类似这样的东西时,我只是在控制台上尝试一下,然后四处挖掘一下。 (我使用 IPython,因此很容易进行制表符检查,但让我们在没有制表符的情况下尝试一下)。

首先,让我们使用

生成一个错误
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

关于python - 从 Python 请求 ConnectionError 获取 Errno?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19370436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com