Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python get an error code from exception

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?

like image 528
Pythonic Guy 21421 Avatar asked Dec 09 '17 00:12

Pythonic Guy 21421


People also ask

How do I get exception error in Python?

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.

How can you catch a specific type of exception in Python?

Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

How do you use try except for value error?

To resolve the ValueError in Python code, a try-except block can be used. The lines of code that can throw the ValueError should be placed in the try block, and the except block can catch and handle the error.

Is exception a runtime error in Python?

All python exceptions are not runtime errors, some are syntax errors as well. If you run the given code, you get the following output. We see that it is syntax error and not a runtime error. Errors or inaccuracies in a program are often called as bugs.


2 Answers

This has worked for me.

  except Exception as e:
    errnum = e.args[0]
like image 198
PerkHaus Avatar answered Oct 04 '22 17:10

PerkHaus


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.

like image 32
François M. Avatar answered Oct 04 '22 19:10

François M.