Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor error handling and get the right stacktrace in Python

I got a lot of code like this :

try:
   # do a lot of stuff
except StuffError as e:
    log.exception(e):
    send_mail_to_admin()
    raise e

For DRY, I wanted to refactor that into :

def post_mortem(log, e):
    log.exception(e):
    send_mail_to_admin() 
    # some other stuff
    raise e

Then do :

try:
   # do a lot of stuff
except StuffError as e:
    post_mortem(log, e)

The trouble is now I don't get the proper stack trace, since the exception is raised from another file.

How can I get the same stack trace I would have had with the first code ?

like image 929
e-satis Avatar asked Feb 02 '26 18:02

e-satis


1 Answers

Pass the exc_info() information also, as one of the parameters like this

post_mortem(log, e, sys.exc_info()[2])

And in the post_mortem

def post_mortem(log, e, traceBack):
    traceback.print_tb(traceBack)

To get the entire stacktrace, you can do like shown in this example

import traceback, sys

def post_mortem(log, e, tb):
    print "".join(traceback.format_list(traceback.extract_stack()[:-2]) + [traceback.format_tb(tb)[0]])

def throwError():
    try:
        raise NameError("I don't like your name")
    except NameError as e:
        post_mortem("", e, sys.exc_info()[2])

def callThrowError():
    throwError()

callThrowError()

Output

  File "/home/thefourtheye/Desktop/Test.py", line 15, in <module>
    callThrowError()
  File "/home/thefourtheye/Desktop/Test.py", line 13, in callThrowError
    throwError()
  File "/home/thefourtheye/Desktop/Test.py", line 8, in throwError
    raise NameError("I don't like your name")
like image 182
thefourtheye Avatar answered Feb 05 '26 09:02

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!