Python 从异常中获取错误代码

Python get an error code from exception

在 python 中,我有处理异常并打印错误代码和消息的代码。

try:
    somecode() #raises NameError
except Exception as e:
    print('Error! Code: {c}, Message, {m}'.format(c = e.code, m = str(e))

但是,e.code 不是获取错误名称 (NameError) 的正确方法,我找不到这个问题的答案。我应该如何获得错误代码?

试试这个:

try:
    somecode() #raises NameError
except Exception as e:
    print('Error! Code: {c}, Message, {m}'.format(c = type(e).__name__, m = str(e)))

阅读 this 以获得更详细的解释。

Python例外没有"codes"。

您可以创建一个自定义异常,它确实有一个名为 code 的 属性,然后您可以访问它并根据需要打印它。

This 答案有一个向自定义异常添加 code 属性 的示例。

因为它return是dictionary of tuple of tuple的对象,我们可以提取代码为

try:
  
  pass

except Exception as e:

  print(e[0][0]['code'] + e[0][0]['message'])

你的问题不清楚,但据我了解,你不是要查找错误的名称(NameError),而是要查找错误代码。这是如何做的。首先,运行 这个:

try:
    # here, run some version of your code that you know will fail, for instance:
    this_variable_does_not_exist_so_this_code_will_fail
except Exception as e:
    print(dir(e))

您现在可以看到 e 中的内容。你会得到这样的东西:

['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'with_traceback']

此列表将包含特殊方法(__x__ 内容),但将以不带下划线的内容结尾。你可以一一尝试找到你想要的,像这样:

try:
    # here, run some version of your code that you know will fail, for instance:
    this_variable_does_not_exist_so_this_code_will_fail
except Exception as e:
    print(e.args)
    print(e.with_traceback)

在这个特定错误的情况下,print(e.args) 是最接近错误代码的,它将输出 ("name 'this_variable_does_not_exist_so_this_code_will_fail' is not defined",).

在这种情况下,只有两件事可以尝试,但在您的情况下,您的错误可能有更多。例如,在我的例子中,一个 Tweepy 错误,列表是:

['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', '__weakref__', 'api_code', 'args', 'reason', 'response', 'with_traceback']

我一一尝试了最后五个。从print(e.args),我得到了([{'code': 187, 'message': 'Status is a duplicate.'}],),从print(e.api_code),我得到了187。所以我发现 e.args[0][0]["code"]e.api_code 会给我正在搜索的错误代码。

这对我有用。

  except Exception as e:
    errnum = e.args[0]