Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get exception description and stack trace which caused an exception, all as a string

I've seen a lot of posts about stack trace and exceptions in Python. But haven't found what I need.

I have a chunk of Python 2.7 code that may raise an exception. I would like to catch it and assign to a string its full description and the stack trace that caused the error (simply all we use to see on the console). I need this string to print it to a text box in the GUI.

Something like this:

try:     method_that_can_raise_an_exception(params) except Exception as e:     print_to_textbox(complete_exception_description(e)) 

The problem is: what is the function complete_exception_description?

like image 861
bluish Avatar asked Dec 30 '10 16:12

bluish


People also ask

How do you capture a stack trace in Python?

Print Stack Trace in Python Using traceback Module The traceback. format_exc() method returns a string that contains the information about exception and stack trace entries from the traceback object. We can use the format_exc() method to print the stack trace with the try and except statements.

What is stack trace in exception?

A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs. The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown.

How do you convert Stacktraceelement to string?

Example: Convert stack trace to a string In the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using printStackTrace() method of the exception and write it in the writer. Then, we simply convert it to string using toString() method.

How do I print a stack trace for exceptions?

Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.


2 Answers

See the traceback module, specifically the format_exc() function. Here.

import traceback  try:     raise ValueError except ValueError:     tb = traceback.format_exc() else:     tb = "No error" finally:     print tb 
like image 71
kindall Avatar answered Sep 18 '22 13:09

kindall


Let's create a decently complicated stacktrace, in order to demonstrate that we get the full stacktrace:

def raise_error():     raise RuntimeError('something bad happened!')  def do_something_that_might_error():     raise_error() 

Logging the full stacktrace

A best practice is to have a logger set up for your module. It will know the name of the module and be able to change levels (among other attributes, such as handlers)

import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) 

And we can use this logger to get the error:

try:     do_something_that_might_error() except Exception as error:     logger.exception(error) 

Which logs:

ERROR:__main__:something bad happened! Traceback (most recent call last):   File "<stdin>", line 2, in <module>   File "<stdin>", line 2, in do_something_that_might_error   File "<stdin>", line 2, in raise_error RuntimeError: something bad happened! 

And so we get the same output as when we have an error:

>>> do_something_that_might_error() Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "<stdin>", line 2, in do_something_that_might_error   File "<stdin>", line 2, in raise_error RuntimeError: something bad happened! 

Getting just the string

If you really just want the string, use the traceback.format_exc function instead, demonstrating logging the string here:

import traceback try:     do_something_that_might_error() except Exception as error:     just_the_string = traceback.format_exc()     logger.debug(just_the_string) 

Which logs:

DEBUG:__main__:Traceback (most recent call last):   File "<stdin>", line 2, in <module>   File "<stdin>", line 2, in do_something_that_might_error   File "<stdin>", line 2, in raise_error RuntimeError: something bad happened! 
like image 36
Russia Must Remove Putin Avatar answered Sep 18 '22 13:09

Russia Must Remove Putin