Richard J
Richard J

Reputation: 7313

Correct way to handle Exception Stack Traces in Python

I am writing some code which can generate Exceptions deep in the stack, and I have a layer nearer the top which catches these exceptions and sends them off for processing by an error handling module. What I would like is for the error handling module to be able to print the stack trace into its error log, but I'm finding it difficult to work out what the way to do this is.

Some notes on the background:

in the constructor of the exception, and while this looks promising in terms of information, it doesn't feel like the "right" way to do it

I don't believe that I'm the first person to ever want to do this, so I must be missing something. Any pointers in the right direction much appreciated.

Upvotes: 6

Views: 1167

Answers (3)

Sebastian Blask
Sebastian Blask

Reputation: 2938

If I understand you right, you want to re-throw an exception while keeping the stacktrace? So you've got a call hierarchy like this:

error_handling_module # you want to print the stacktrace here
|
something_else
|
module_excepting_and_rethrowing
|
something_else
|
module_raising_an_error

In you module_excepting_and_rethrowing you can do:

except Exception:
   exc_type, exc_value, exc_traceback = sys.exc_info()
   raise NewException, exc_value, exc_traceback

In Python3 you can also do:

 except Exception as e:
     raise NewException from e

Upvotes: 0

Lie Ryan
Lie Ryan

Reputation: 64845

How about adding some decorator in the functions that you want to protect? For example:

@onerrorignore
def foo(a, b, c):
    ...

the decorator would look something like:

def onerrorignore(f):
    def _f(*args, **kwargs):
        try:
            ret = f()
        except:
            error_handler.handle(sys.exc_info())
        else:
            return ret
    return _f

Upvotes: 0

Ali Afshar
Ali Afshar

Reputation: 41643

Your first line on handling the exception could be:

exc_type, exc_value, exc_traceback = sys.exc_info()

You can store these variables or pass them any how you like, then later use the traceback module to display them.

Upvotes: 2

Related Questions