python - 全局错误处理以获得更好的 KeyError 处理
问题描述
我想改进KeyError
异常消息以查看字典中的键。
示例: 之前:KeyError 'x' 之后:KeyError 'y'(键:['a','b'])
原因是我一直在浪费时间来调试发生的事情以及字典中的键。我们有一个大型商业计划,所以我想要一个全局错误处理程序,并且异常可以在任何深度发生。一个简单的尝试,除了 KeyError 并不能解决问题,因为我不再有权访问该字典。
有没有办法全局覆盖 KeyError 异常以存储和访问已使用的失败字典?
解决方案
这是我现在使用的解决方案,因为我们无法覆盖内置函数。
class LXKeyError(KeyError):
def __init__(self, item, d):
self.item = item
self.d = d
def __str__(self):
keys = str(list(self.d.keys()))
if len(keys) > 1000: # (13 (max field length in uf) + 4 ("', '")) * 50 (max number of fields we want to print) = 850
keys = f'{keys[:995]} ...'
return f'Unknown key in dict: {self.item!r} (keys: {keys})'
class LXDict(dict):
def __missing__(self, key):
raise LXKeyError(key, self)
测试:
orig_d = {'a': 'a', 'b': 'b', '1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': '', '9': '', '10': '', '11': '', '12': '',
'13': '', '14': '', '15': '', '16': '', '17': '', '18': '', '19': '', '20': '',
}
d = LXDict(orig_d)
try:
d['x']
assert False, f'Should not arrive here'
except KeyError as ex:
print(ex)
推荐阅读
- python - 矩阵减法类似于张量流中的矩阵乘法
- php - Laravel webdav和文件系统无法访问驱动器
- javascript - 我应该为这个 Tampermonkey 脚本选择哪个元素?还是可以等到所有内容加载完毕?
- html - 寻找从 Python3 读取 HTML 文件中的表格内容的方法
- graphql - GitHub GraphQL 获取未归档的存储库
- infinite-loop - 随机循环
- xml - 如何使用 XmlNode() 作为 VB.NET 中 web 服务的结果?
- r - R - 选择最后 2 列
- bash - 并行执行多个作业时指定 SLURM 资源
- python - 矩阵中具有最大最小值的行总和