Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch python exception and save traceback text as string

I'm trying to write a nice error handler for my code, so that when it fails, the logs, traceback and other relevant info get emailed to me.

I can't figure out how to take an exception object and extract the traceback.

I find the traceback module pretty confusing, mostly because it doesn't deal with exceptions at all. It just fetches some global variables from somewhere, assuming that I want the most recent exception. But what if I don't? What if I want to ignore some exception in my error handler? (e.g. if I fail to send me email and want to retry.)

What I want

import traceback as tb

# some function that will fail after a few recursions
def myfunc(x):
   assert x > 0, "oh no"
   return myfunc(x-1)

try:
    myfunc(3)
except Exception as e:
    traceback_str = tb.something(e)

Note that tb.something takes e as an argument.

There's lots of questions on Stack Overflow about using the traceback module to get a traceback string. The unique thing about this question is how to get it from the caught exception, instead of global variables.

Result:

traceback_str contains the string:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in myfunc
  File "<stdin>", line 3, in myfunc
  File "<stdin>", line 3, in myfunc
  File "<stdin>", line 2, in myfunc
AssertionError: oh no

Note that it contains not just the most recent function call, but the whole stack, and includes the "AssertionError" at the end

like image 561
falsePockets Avatar asked Jul 17 '20 10:07

falsePockets


People also ask

How do I print traceback of exception in Python?

Method 2: By using print_exception() method. This method prints exception information and stack trace entries from traceback object tb to file. Parameters: This method accepts the following parameters: if tb argument is not None, it prints a header Traceback (most recent call last):

How do I get an exception to a text 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 do I print an exception stack trace?

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.


1 Answers

The correct function for tb.something(e) is

''.join(tb.format_exception(None, e, e.__traceback__))
like image 118
falsePockets Avatar answered Oct 11 '22 23:10

falsePockets