You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从ExceptionGroup中提取Exception?(基于Trio框架)

从Trio的ExceptionGroup中提取异常

ExceptionGroup是包含多个子异常的容器,它的exceptions属性存储了所有子异常的列表,你可以通过以下方式提取:

直接访问单个异常

如果明确知道目标异常在列表中的位置,直接索引exceptions属性即可:

# 假设exc是你捕获到的ExceptionGroup实例
first_exception = exc.exceptions[0]
print(first_exception)  # 输出对应的HTTPStatusError

遍历处理所有异常

如果需要批量处理所有子异常,直接循环exceptions列表:

for sub_exc in exc.exceptions:
    # 判断异常类型并针对性处理
    if isinstance(sub_exc, HTTPStatusError):
        print(f"HTTP错误详情: {sub_exc}")
        # 这里可添加日志记录、重试逻辑等操作

Trio场景下的完整示例

结合你给出的场景,完整的捕获和提取代码如下:

import trio
from httpx import HTTPStatusError

async def api_request_task():
    # 模拟抛出你遇到的HTTP错误
    raise HTTPStatusError(
        "Client error '400 Bad Request' for url 'https://api.fastly.com/service/xyz/acl/xyz/entries'",
        request=None, response=None
    )

async def main():
    try:
        async with trio.Nursery() as nursery:
            nursery.start_soon(api_request_task)
    except ExceptionGroup as exc:
        # 提取第一个异常
        target_exc = exc.exceptions[0]
        print(f"提取到的异常: {target_exc}")
        # 遍历处理所有子异常
        for sub_exc in exc.exceptions:
            if isinstance(sub_exc, HTTPStatusError):
                print(f"处理400错误: {sub_exc}")

if __name__ == "__main__":
    trio.run(main)

内容的提问来源于stack exchange,提问作者Brian C.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 13:42:12