In python, I have code that handles exceptions and prints error codes and messages.
try:
somecode() #raises NameError
except Exception as e:
print('Error! Code: {c}, Message, {m}'.format(c = e.code, m = str(e))
However, e.code
is not the proper way to get the error name (NameError), and I cannot find the answer to this. How am I supossed to get the error code?
Your question is unclear, but from what I understand, you do not want to find the name of the error (NameError
), but the error code. Here is how to do it. First, run this:
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))
You can now see what is in e
. You will get something like this:
['__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']
This list will include special methods (__x__
stuff), but will end with things without underscores. You can try them one by one to find what you want, like this:
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)
In the case of this specific error, print(e.args)
is the closest you'll get to an error code, it will output ("name 'this_variable_does_not_exist_so_this_code_will_fail' is not defined",)
.
In this case, there is only two things to try, but in your case, your error might have more. For example, in my case, a Tweepy error, the list was:
['__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']
I tried the last five one by one. From print(e.args)
, I got ([{'code': 187, 'message': 'Status is a duplicate.'}],)
, and from print(e.api_code)
, I got 187
. So I figured out that either e.args[0][0]["code"]
or e.api_code
would give me the error code I'm searching for.