[New-bugs-announce] [issue42526] Exceptions in asyncio.Server callbacks are not retrievable

Tom report at bugs.python.org
Tue Dec 1 10:42:34 EST 2020

New submission from Tom <tom at collider.in>:

Consider this program:

    import asyncio

    async def handler(r, w):
        raise RuntimeError

    async def main():
        server = await asyncio.start_server(handler, host='localhost', port=1234)
        r, w = await asyncio.open_connection(host='localhost', port=1234)
        await server.serve_forever()


The RuntimeError is not retrievable via the serve_forever coroutine. To my
knowledge, there is no feature of the asyncio API which causes the server to
stop on an exception and retrieve it. I have also tried wrapping serve_forever
in a Task, and waiting on the coro with FIRST_EXCEPTION.

This severely complicates testing asyncio servers, since failing tests hang
forever if the failure occurs in a callback.

It should be possible to configure the server to end if a callback fails, e.g.
by a 'stop_on_error' kwarg to start_server (defaulting to False for

I know this isn't a technical problem, since AnyIO, which uses asyncio, does
this by default. This equivalent program ends after the exception:

    import anyio

    async def handler(client):
        raise RuntimeError

    async def main():
        async with anyio.create_task_group() as tg:
            listener = await anyio.create_tcp_listener(local_host='localhost', local_port=1234)
            await tg.spawn(listener.serve, handler)
            async with await anyio.connect_tcp('localhost', 1234) as client:


components: asyncio
messages: 382265
nosy: asvetlov, tmewett, yselivanov
priority: normal
severity: normal
status: open
title: Exceptions in asyncio.Server callbacks are not retrievable
versions: Python 3.7

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list