代码之家  ›  专栏  ›  技术社区  ›  Denny Weinberg

全局错误处理以更好地处理密钥错误

  •  0
  • Denny Weinberg  · 技术社区  · 4 年前

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

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

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

    0 回复  |  直到 4 年前
        1
  •  0
  •   Denny Weinberg    4 年前

    这是我现在使用的解决方案,因为我们不能覆盖内置的。

    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)