首页 > 解决方案 > 全局错误处理以获得更好的 KeyError 处理

问题描述

我想改进KeyError异常消息以查看字典中的键。

示例: 之前:KeyError 'x' 之后:KeyError 'y'(键:['a','b'])

原因是我一直在浪费时间来调试发生的事情以及字典中的键。我们有一个大型商业计划,所以我想要一个全局错误处理程序,并且异常可以在任何深度发生。一个简单的尝试,除了 KeyError 并不能解决问题,因为我不再有权访问该字典。

有没有办法全局覆盖 KeyError 异常以存储和访问已使用的失败字典?

标签: python

解决方案


这是我现在使用的解决方案,因为我们无法覆盖内置函数。

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)

推荐阅读