pythonpython-3.xpython-trio

How to get an Exception out of an ExceptionGroup?


If I have an ExceptionGroup how do I get the Exception out of it? I happen to be using Trio.

>>> exc
>>> ExceptionGroup('Exceptions from Trio nursery', [HTTPStatusError("Client error 
'400 Bad Request' for url 'https://api.fastly.com/service/xyz/acl/xyz/entries'
\nFor more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400")])

Solution

  • This is what worked for me:

    except* HTTPError as exc:
        httpexps, others = exc.split(HTTPError)
        httpexp = httpexps.exceptions[0]
        if httpexp.response.status_code == 400:
            # etc etc
    

    The except* HTTPError catches any group with the HTTPError.

    The exc.split(HTTPError) splits the group into two new groups, one that is only HTTPError and one that is everything else.

    The httpexps.exceptions[0] gets the first exception in that group.