Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the traceback object ( sys.exc_info()[2] , same as sys.exc_traceback ) as a string?

I have a function which catches all exceptions, and I want to be able to get the traceback as a string within this function.

So far this is not working:

def handle_errors(error_type, error_message, error_traceback):
    """catch errors"""
    import traceback
    error = {}
    error['type'] = error_type.__name__
    error['message'] = str(error_message)
    error['file'] = os.path.split(error_traceback.tb_frame.f_code.co_filename)[1]
    error['line'] = error_traceback.tb_lineno
    error['traceback'] = repr(traceback.print_tb(error_traceback))
    ### finalise error handling and exit ###

sys.excepthook = handle_errors

It's the error['traceback'] line which is wrong. Do i even need to use the traceback module?

As per this other vaguely similar question, I have tried:

error['traceback'] = repr(error_traceback.print_exc())

...but this gives an error:

Error in sys.excepthook:
Traceback (most recent call last):
  File "xxxxxxxxxxx", line 54, in handle_errors
    error['traceback'] = repr(error_traceback.print_exc())
AttributeError: 'traceback' object has no attribute 'print_exc'
like image 258
mulllhausen Avatar asked Nov 27 '13 11:11

mulllhausen


People also ask

How do I fix Python traceback error?

The traceback error also shows the type of error and information about that error. The above case is IndexError: list index out of range . You can fix it using the valid index number to retrieve an item from a list.

What will be the output of SYS Exc_info () function?

The sys. exc_info function returns a 3- tuple with the exception, the exception's parameter, and a traceback object that pinpoints the line of Python that raised the exception.

What is a traceback error?

The error message line of the NameError traceback gives you the name that is missing. In the example above, it's a misspelled variable or parameter to the function that was passed in. A NameError will also be raised if it's the parameter that you misspelled: >>> >>> def greet(persn): ...


1 Answers

Use traceback.format_tb() instead of print_tb() to get the formatted stack trace (as a list of lines):

error['traceback'] = ''.join(traceback.format_tb(error_traceback))

print_tb() directly prints the traceback, that's why you get None as a result (that's the default for any Python function that doesn't return anything explicitely).

like image 91
Lukas Graf Avatar answered Oct 20 '22 03:10

Lukas Graf