首页 > 解决方案 > 处理 glib 主循环中未捕获的错误

问题描述

我想在 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()

标签: pythonasynchronousgtkglib

解决方案


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

推荐阅读