python runtime_error ai_generated true

ExceptionGroup: TaskGroup 中存在未处理的错误(1 个子异常)

ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)

ID: python/asyncio-taskgroup-exceptiongroup

其他格式: JSON · Markdown 中文 · English
80%修复率
89%置信度
0证据数
2024-09-25首次发现

版本兼容性

版本状态引入弃用备注
3.11 active — — —
3.12 active — — —

根因分析

asyncio.TaskGroup(3.11+)内部的异常被包装在 ExceptionGroup 中;捕获原始异常类型的调用方永远看不到它。

English

An exception inside asyncio.TaskGroup (3.11+) is wrapped in an ExceptionGroup; callers that catch the original exception type never see it.

generic

解决方案

  1. 95% 成功率
    Catch ExceptionGroup and use except*:
    
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(work())
    except* ValueError as eg:
        handle(eg.exceptions)
  2. 90% 成功率
    Inspect sub-exceptions:
    
    except ExceptionGroup as eg:
        for exc in eg.exceptions:
            logger.error('task failed', exc_info=exc)
  3. 85% 成功率
    For libraries that don't support except*, unwrap manually:
    
    def unwrap(eg): return eg.exceptions[0] if len(eg.exceptions) == 1 else eg

无效尝试

常见但无效的做法:

  1. 90% 失败

    The ValueError is nested inside ExceptionGroup; the outer except never matches.

  2. 70% 失败

    Swallows the group but is bad practice; masks other failures.

  3. 95% 失败

    Touches private state; unrelated to exception wrapping.