Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions from any task in an event loop?

I would like to stop the program, i.e. the event loop, if any task anywhere raises an unhandled exception. The normal behaviour is that you get a Task exception was never retrieved error message and the individual task stops, but the loop continues to run all other tasks.

For example:

import asyncio

async def foo():
    while True:
        await asyncio.sleep(1)
        print("hi")

async def bug():
    await asyncio.sleep(2)
    raise TypeError

loop = asyncio.get_event_loop()
loop.create_task(foo())
loop.create_task(bug())
loop.run_forever()

Output:

"hi"
"hi"
Task exception was never retrieved
future: <Task finished coro=<bug() done, defined at <...>:9> exception=TypeError()>
Traceback (most recent call last):
  File "<ipython-input-4-bd8651340a75>", line 11, in bug
    raise TypeError
TypeError
"hi"
"hi"
"hi"
...

My project contains many dozens of coroutines spread over many files which add each other to the loop with loop.create_task(foo()) so because they don't await each other, you cannot simply handle one or two entry point coroutines in the main file and have errors bubble up.

like image 434
sphere Avatar asked Oct 12 '25 08:10

sphere


1 Answers

I think I've found what I'm looking for with loop.set_exception_handler(handler)

like image 172
sphere Avatar answered Oct 15 '25 11:10

sphere