我想在glib主循环中添加一些类似默认错误处理程序的东西以捕获和处理未捕获的错误。
GLib主循环不会在出现错误时停止执行,所以我想GLib代码中存在错误处理程序,它只是打印它然后继续好像什么都没发生一样。我想扩展这个错误处理程序来做一些定制的东西。
from gi.repository import GLib
def throw():
raise ValueError('catch this error somehow without try and catch')
def stop():
print('exit')
exit()
GLib.timeout_add(100, throw)
GLib.timeout_add(200, stop)
GLib.MainLoop().run()
这将打印
Traceback (most recent call last):
File "gtkasyncerror.py", line 7, in throw
raise ValueError('catch this error somehow without try and catch')
ValueError: catch this error somehow without try and catch
exit
这就是我希望它的工作方式:
def error_handler(e):
# do funny stuff
# the ValueError from above should be in e
loop = GLib.MainLoop()
loop.error_handler = error_handler
GLib.MainLoop().run()
https://stackoverflow.com/a/6598286/4417769
import sys
from gi.repository import GLib
def throw():
raise ValueError('catch this error somehow without try and catch')
try:
raise ValueError('this should not be handled by error_handler')
except ValueError as e:
pass
def stop():
print('exit')
exit()
def error_handler(exctype, value, traceback):
print('do funny stuff,', value)
GLib.timeout_add(100, throw)
GLib.timeout_add(200, stop)
sys.excepthook = error_handler
GLib.MainLoop().run()
输出:
do funny stuff, catch this error somehow without try and catch
exit