Skip to content

__cause__ and __context__ on user exceptions are lost when running with exception groups #191

@jakkdl

Description

@jakkdl

This code will fully lose the TypeError as the __context__ from the exception, due to python-trio/flake8-async#298

async def test_user_exception_cause(nursery) -> None:
    async def handler(request):
        await request.accept()
    server = await nursery.start(serve_websocket, handler, HOST, 0, None)
    async with open_websocket(HOST, server.port, RESOURCE, use_ssl=False):
        try:
            raise TypeError
        except TypeError:
            raise ValueError

The offending code for this example is

except _TRIO_EXC_GROUP_TYPE as e:
# user_error, or exception bubbling up from _reader_task
if len(e.exceptions) == 1:
raise e.exceptions[0]

which implicitly sets __context__ to the caught group, and the user exception inside the group is the same exception, so it simultaneously loses its old __context__.

The fix is to sprinkle a bunch of copy.copy() calls. Given that we have a finally it's not an alternative to raise the exception outside of the exception handler.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions