Capture Nested Exceptions in Python

Viewed 6723

I have set of Python scripts which are calling functions in a nested way. For each of these functions I have a try, except statement to capture every exception and print them. I would like to send an e-mail alert containing the complete sequence of exceptions encountered during the execution. Example:

import sys

def SendAlert(ErrorMessage):
    try:
        #send email alert with error message
        #[...]
    except:
        print(str(sys.exc_info()))
        return(sys.exc_info())

def ParentFunction():
    try:
        #call ChildFunction
        ChildResult = ChildFunction()

        #do stuff with ChildResult
        #[...]
        return ParentResult
    except:
        ErrorMessage = str(sys.exc_info())
        print(ErrorMessage)
        SendAlert(ErrorMessage)

def ChildFunction():
    try:
        #do stuff
        #[...]
        return ChildResult
    except:
        print(str(sys.exc_info()))
        return(sys.exc_info())

#main
if __name__ == '__main__':
    Result = ParentFunction()

The code above would behave as follow in case of error in ChildFunction which is the most nested function:

  • ChildFunction encounters an exception it will print it and return the error message to ParentFunction
  • ParentFunction will fail because ChildResult contains an error message and not a valid value
  • ParentFunction will trigger and exception and send its own error message in the e-mail alert

In addition to the error message from ParentFunction, I would like the e-mail alert to contain the error message from ChildFunction. Note that I would like to avoid passing ChildResult variable to SendAlert function in the except statement of ParentFunction because in real life my program has a lot of nested functions and it would mean passing the result variable of every single function into the except statement.

How would you achieve this? Is there a way to access the complete sequence of errors triggered by the whole program?

Thanks

2 Answers
Related