我抓住并打印Python Requests ConnectionErrors就好了:
except requests.exceptions.ConnectionError as e:
logger.warning(str(e.message))
Run Code Online (Sandbox Code Playgroud)
它打印出如下消息:
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)
Run Code Online (Sandbox Code Playgroud)
和
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)
Run Code Online (Sandbox Code Playgroud)
还有很多其他人.我想知道的是,什么是最好的,最Pythonic的方式来获得在消息中显示的错误?我希望有一个可靠的系统来捕获问题,并尽可能向用户提供有用和相关的错误消息.据我所知,ConnectionError是BaseException的间接死因,没有新的属性或方法被添加到BaseException提供的范围之外.我对使用正则表达式犹豫不决,因为在我看来,我冒着假设所有错误消息在所有地方以相同方式格式化的风险.