Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python traceback.print_exc() returns 'None'

This function is supposed to catch exceptions in the main execution. If there is an exception it should print out the error with log.error(traceback.print_exc()) and clean up with exit_main().

def main():
    try:
        exec_app()
    except KeyboardInterrupt:
        log.error('Error: Backup aborted by user.')
        exit_main()
    except Exception:
        log.error('Error: An Exception was thrown.')
        log.error("-" * 60)
        log.error(traceback.print_exc())
        log.error("-" * 60)
        exit_main()

Unfortunately log.error(traceback.print_exc()) does only return None if there is an exception. How can I make traceback print the full error report in this case?

PS: I use python 3.4.

like image 367
Rotareti Avatar asked Oct 25 '16 12:10

Rotareti


People also ask

What is traceback Print_exc?

traceback. print_exc(limit = None, file = None, chain = True) : This is a shorthand for print_exception(*sys. exc_info(), limit, file, chain). traceback. print_last(limit = None, file = None, chain = True) : It works only after an exception has reached an interactive prompt.

Why am I getting traceback errors in Python?

The error message line of the NameError traceback gives you the name that is missing. In the example above, it's a misspelled variable or parameter to the function that was passed in.

What are common traceback errors in Python?

Some of the common traceback errors are:KeyError. TypeError. valueError. ImportError /ModuleNotFound.

How do I print a stack trace in Python?

Method 1: By using print_exc() method. This method prints exception information and stack trace entries from traceback object tb to file.


2 Answers

From its __doc__:

Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'

That is, it isn't supposed to return anything, its job is to print. If you want the traceback as a string to be logged, use traceback.format_exc() instead.

like image 89
Scott Hunter Avatar answered Sep 28 '22 09:09

Scott Hunter


I usually use traceback.print_exc() just for debugging. In your case, to log your exception you can simply do the following:

try:
    # Your code that might raise exceptions
except SomeSpecificException as e:
    # Do something (log the exception, rollback, etc)
except Exception as e:
    log.error(e)  # or log(e.message) if you want to log only the message and not all the error stack
like image 34
ettanany Avatar answered Sep 28 '22 09:09

ettanany