如果我抓到 KeyError
,我怎么知道什么查找失败了?
def poijson2xml(location_node, POI_JSON):
try:
man_json = POI_JSON["FastestMan"]
woman_json = POI_JSON["FastestWoman"]
except KeyError:
# How can I tell what key ("FastestMan" or "FastestWoman") caused the error?
LogErrorMessage ("POIJSON2XML", "Can't find mandatory key in JSON")
原文由 QuestionC 发布,翻译遵循 CC BY-SA 4.0 许可协议
以当前异常为例(在本例中我使用了它
as e
);然后对于KeyError
第一个参数是引发异常的键。因此我们可以这样做:这样,您就有了违规密钥存储在
cause
中。扩展您的示例代码,您的日志可能如下所示:
应该注意的是
e.message
在 Python 2 中有效,但在 Python 3 中无效,因此不应使用它。