Thursday 9 November 2017

Get complete error traceback without terminating program

Django Admin Action
   For some try except cases its difficult to get the appropriate error traceback only using 'Exception' keyword in try..except.
But for such cases python has a module named 'traceback' which can be used in such situations.

Consider the following piece of code from myscript.py
try:
    test_variable = tuple(range(0,10))
    test_variable.append(10)
except Exception as error:
    print "[ - ] Error:", error
Output would look like:
     [ - ] Error: AttributeError: 'tuple' object has no attribute 'append'

Now issue with above error response is vagueness in details regarding the error. In order to get complete error traceback we can use python 'traceback' module.

Now the code would look like:
import traceback

try:
    test_variable = tuple(range(0,10))
    test_variable.append(10)
except:
    print "[ - ] Error:", traceback.print_exc()

Output will be:
[ - ] Error: Traceback (most recent call last):
File "/home/myscript.py", line 5, in <module>
    a.append(15)
AttributeError: 'tuple' object has no attribute 'append'

We can also use python sys module to get the exception info of the error and print it. For example:

import traceback
import sys

try:
    exc_info = sys.exc_info()
    test_variable = tuple(range(0,10))
    test_variable.append(10)
except:
    traceback.print_exception(*exc_info)
    del exc_info

Output will be same as one shown above.

For more usages regarding trackback module can be found here.