在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)的正确方法,我找不到答案。我该如何获取错误代码?
在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)的正确方法,我找不到答案。我该如何获取错误代码?
这对我很有效。
except Exception as e:
errnum = e.args[0]
您的问题不太清楚,但从我理解的来看,您并不想找到错误的名称(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",)
。['__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
会给我所寻找的错误代码。
试试这个:
try:
somecode() #raises NameError
except Exception as e:
print('Error! Code: {c}, Message, {m}'.format(c = type(e).__name__, m = str(e)))
阅读this以获取更详细的解释。
由于它返回字典的元组的元组对象,因此我们可以提取代码如下:
try:
pass
except Exception as e:
print(e[0][0]['code'] + e[0][0]['message'])
type(e).__name__
。 - Michael Butschere.message
是什么意思? - user1767754print( dir(e) )
查看e
中有哪些字段。每个异常可能具有不同的字段。 - furas