Krita Source Code Documentation
Loading...
Searching...
No Matches
excepthook.py
Go to the documentation of this file.
2# SPDX-License-Identifier: GPL-3.0-or-later
3#
4
5"""
6Exception hook
7If some unexpected error occurs it can be shown in a nice looking dialog.
8Especially useful is the traceback view.
9
10Things to extend: Clicking on the filename should open an editor.
11Things to consider: Mail exceptions, copy to clipboard or send to bug tracker.
12"""
13import sys
14import traceback
15import atexit
16
17try:
18 from PyQt6.QtCore import pyqtSlot, Qt
19 from PyQt6.QtWidgets import QApplication, QDialog
20except:
21 from PyQt5.QtCore import pyqtSlot, Qt
22 from PyQt5.QtWidgets import QApplication, QDialog
23
24from excepthook_ui import Ui_ExceptHookDialog
25
26
27def on_error(exc_type, exc_obj, exc_tb):
28 """
29 This is the callback function for sys.excepthook
30 """
31 dlg = ExceptHookDialog(exc_type, exc_obj, exc_tb)
32 dlg.show()
33 dlg.exec()
34
35
36def show_current_error(title=None):
37 """
38 Call this function to show the current error.
39 It can be used inside an except-block.
40 """
41 dlg = ExceptHookDialog(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], title)
42 dlg.show()
43 dlg.exec()
44
45
46def install():
47 "activates the error handler"
48 sys.excepthook = on_error
49
50
52 "removes the error handler"
53 sys.excepthook = sys.__excepthook__
54
55atexit.register(uninstall)
56
57
58class ExceptHookDialog(QDialog):
59
60 def __init__(self, exc_type, exc_obj, exc_tb, title=None):
61 QDialog.__init__(self)
63 self.ui.setupUi(self)
64 if title:
65 self.setWindowTitle(self.windowTitle() + ": " + title)
66 msg = "%s: %s" % (exc_type.__name__, exc_obj)
67 self.ui.exceptionLabel.setText(msg)
68 html = "\n".join(traceback.format_exception(exc_type, exc_obj, exc_tb))
69 self.ui.tracebackBrowser.setText(html)
70 self.resize(650, 350) # give enough space to see the backtrace better
71
72 @pyqtSlot()
74 self.close()
75
76
77if __name__ == "__main__":
78 # Some tests:
79 app = QApplication(sys.argv)
80 install()
81 print("Triggering error 1")
82 try:
83 fail = 1 / 0
84 except:
85 show_current_error("Using inside except")
86 print("Triggering error 2")
87 fail2 = 1 / 0
88 print("This will never be reached because excepthook")
89 print("complains about fail2")
__init__(self, exc_type, exc_obj, exc_tb, title=None)
Definition excepthook.py:60
show_current_error(title=None)
Definition excepthook.py:36
on_error(exc_type, exc_obj, exc_tb)
Definition excepthook.py:27