Python traceback.print_exc() returns 'None'
Asked Answered
H

2

10

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.

Hardily answered 25/10, 2016 at 12:38 Comment(2)
Which type of exception are you expecting to be logged with traceback.print_exc()? it would logs all exceptions except KeyboardInterruptGodavari
Yes. It should handle all exceptions that I haven't caught inside exec_app().Hardily
D
21

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.

Dreary answered 25/10, 2016 at 12:41 Comment(0)
G
1

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
Godavari answered 25/10, 2016 at 13:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.