1

I'd like to add something like a default error handler to the glib mainloop to catch and handle uncaught errors.

The GLib mainloop won't stop execution on errors, so I guess some sort of error handler exists in the GLib code that just prints it and then continues as if nothing happened. I'd like to extend that error handler to do some custom stuff.

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()

This prints

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

And this is how I would like it to work:

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()
sezanzeb
  • 816
  • 8
  • 20

1 Answers1

0

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()

output:

do funny stuff, catch this error somehow without try and catch
exit
sezanzeb
  • 816
  • 8
  • 20