17

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?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Pythonic Guy 21421
  • 371
  • 1
  • 3
  • 8

5 Answers5

8

This has worked for me.

  except Exception as e:
    errnum = e.args[0]
PerkHaus
  • 89
  • 1
  • 2
4

Python exceptions do not have "codes".

You can create a custom exception that does have a property called code and then you can access it and print it as desired.

This answer has an example of adding a code property to a custom exception.

Dustin Wyatt
  • 4,046
  • 5
  • 31
  • 60
2

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.

François M.
  • 4,027
  • 11
  • 30
  • 81
-2

Try this:

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

Read this for a more detailed explanation.

63677
  • 282
  • 3
  • 7
-2

Since it return the object of tuple of tuple of dictionary, we can extract the code as

try:
  
  pass

except Exception as e:

  print(e[0][0]['code'] + e[0][0]['message'])
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
M.G
  • 1
  • 1