如何在Python中获取嵌套异常的消息值



我有一个异常,看起来像这样:

exc = ProtocolError('Connection Aborted', BadStatusLine('No status line received'))

如何访问No status line received部分?

以下是示例情况:

def some_function():
raise ProtocolError('Connection Aborted', BadStatusLine('No status line received'))
def some_other_function():
try:
some_function()
except Exception as exc:
if exc.message:
details = exc.message
else:
details = exc

在上面的代码中,我试图检查返回的异常是否有消息,如果有,我应该将其写入数据库,但当我调用exc.message时,它会返回一个空字符串,当我调用exc时,它返回:

bson.errors.InvalidDocument:无法对对象进行编码:ProtocolError("连接已中止",BadStatusLine("未接收到状态行",((,类型:<类"urllib3.exceptions.ProtocolError">

所以我无法将其写入数据库,因为它的类型是Exception而不是string,我需要做的是查看返回的Exception中是否有另一个嵌套的Exception,并获取它的消息。

我找不到获取内部消息或异常的最佳方法,但为了快速帮助,我编写了一个实用函数,通过使用正则表达式将返回内部异常或消息完整的代码如下

from urllib3.exceptions import ProtocolError
from http.client import BadStatusLine
import re
def FetchInnerExceptions(exc):
result = []
messages = str(exc).split(',')
for msg in messages:
m = re.search('''(?<=')s*[^']+?s*(?=')''', msg)
if m is not None or m != '':
result.append(m.group().strip())
return result
def some_function():
raise ProtocolError('Connection Aborted', BadStatusLine('No status line received'))
def some_other_function():
try:
some_function()
except Exception as exc:
e = FetchInnerExceptions(exc)
print(e) #dumps all array or use index e[1] for your required message
some_other_function()

最新更新