57 lines
1.7 KiB
Python
57 lines
1.7 KiB
Python
# Adapted from http://timlehr.com/python-exception-hooks-with-qt-message-box/
|
|
|
|
import sys
|
|
import traceback
|
|
from PyQt4 import QtCore, QtGui
|
|
|
|
|
|
def show_exception_box(log_msg):
|
|
"""
|
|
Checks if a QApplication instance is available and shows a messagebox with the exception message
|
|
If unavailable (non-console application), log an additional notice.
|
|
"""
|
|
print "[ERROR]: An unexpected error occured: %s" % log_msg
|
|
if QtGui.QApplication.instance() is not None:
|
|
QtGui.QMessageBox.critical(
|
|
None,
|
|
"FOFB: Unexpected error",
|
|
"""
|
|
<b>An unexpected error occured:</b>
|
|
<br>
|
|
<br>
|
|
%s
|
|
""" % log_msg.replace("\n", "<br>")
|
|
)
|
|
|
|
|
|
class UncaughtHook(QtCore.QObject):
|
|
_exception_caught = QtCore.Signal(object)
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super(UncaughtHook, self).__init__(*args, **kwargs)
|
|
|
|
# this registers the exception_hook() function as hook with the Python interpreter
|
|
sys.excepthook = self.exception_hook
|
|
|
|
# connect signal to execute the message box function always on main thread
|
|
self._exception_caught.connect(show_exception_box)
|
|
|
|
def exception_hook(self, exc_type, exc_value, exc_traceback):
|
|
"""Function handling uncaught exceptions.
|
|
It is triggered each time an uncaught exception occurs.
|
|
"""
|
|
if issubclass(exc_type, KeyboardInterrupt):
|
|
# ignore keyboard interrupt to support console applications
|
|
sys.__excepthook__(exc_type, exc_value, exc_traceback)
|
|
else:
|
|
exc_info = (exc_type, exc_value, exc_traceback)
|
|
log_msg = "\n".join([
|
|
"".join(traceback.format_tb(exc_traceback)),
|
|
"%s: %s" % (exc_type.__name__, exc_value)
|
|
])
|
|
# trigger message box show
|
|
self._exception_caught.emit(log_msg)
|
|
|
|
# create a global instance of our class to register the hook
|
|
qt_exception_hook = UncaughtHook()
|