Normally unhandled exceptions go to the stdout (or stderr?), I am building an app where I want to pass this info to the GUI before shutting down and display it to the user and, at the same time I want to write it to a log file. So, I need an str with the full text of the exception.
How can I do this?
Use sys.excepthook to replace the base exception handler. You can do something like:
import sys
from PyQt4 import QtGui
import os.path
import traceback
def handle_exception(exc_type, exc_value, exc_traceback):
""" handle all exceptions """
## KeyboardInterrupt is a special case.
## We don't raise the error dialog when it occurs.
if issubclass(exc_type, KeyboardInterrupt):
if QtGui.qApp:
QtGui.qApp.quit()
return
filename, line, dummy, dummy = traceback.extract_tb( exc_traceback ).pop()
filename = os.path.basename( filename )
error = "%s: %s" % ( exc_type.__name__, exc_value )
QtGui.QMessageBox.critical(None,"Error",
"<html>A critical error has occured.<br/> "
+ "<b>%s</b><br/><br/>" % error
+ "It occurred at <b>line %d</b> of file <b>%s</b>.<br/>" % (line, filename)
+ "</html>")
print "Closed due to an error. This is the full error report:"
print
print "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
sys.exit(1)
# install handler for exceptions
sys.excepthook = handle_exception
This catches all unhandled exceptions, so you don't need a try...except block at the top level of your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With