处理来自glib mainloop的未捕获错误

问题描述

我想在glib mainloop中添加类似错误处理程序的内容 捕获并处理未捕获的错误

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