Python中如何获取嵌套异常的内部错误消息值?
异常内容提取方案
针对当前ProtocolError场景的直接解法
urllib3.exceptions.ProtocolError异常不存在message属性,所有传入的参数都存储在Python异常通用的args元组中:
- 元组第1位是固定提示字符串
Connection Aborted - 元组第2位就是嵌套的
BadStatusLine异常实例,该实例的args元组第1位就是你要提取的No status line received内容
可直接使用如下代码处理:
from urllib3.exceptions import ProtocolError def some_other_function(): try: some_function() except Exception as exc: details = "" if isinstance(exc, ProtocolError) and len(exc.args) >= 2: nested_exc = exc.args[1] if hasattr(nested_exc, "args") and len(nested_exc.args) > 0: details = nested_exc.args[0] # 兜底逻辑:未取到嵌套内容时直接将异常转为字符串 if not details: details = str(exc) # 此时details为字符串类型,可直接写入数据库
通用嵌套异常提取方法
如果需要兼容所有可能的嵌套异常场景,可以使用递归方法提取全层级异常信息:
def extract_full_exception_msg(exc): msg_parts = [str(exc)] for arg in getattr(exc, "args", []): if isinstance(arg, Exception): msg_parts.append(extract_full_exception_msg(arg)) return " | ".join(msg_parts)
调用时直接执行details = extract_full_exception_msg(exc)即可拿到拼接好的全量异常字符串,不会出现非字符串类型无法序列化写入数据库的问题。
内容的提问来源于stack exchange,提问作者SLDem
相关产品推荐
相关产品推荐

