python runtime_error ai_generated true

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

ID: python/asyncio-taskgroup-exceptiongroup

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2024-09-25First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.11 active — — —
3.12 active — — —

Root Cause

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

generic

中文

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

Workarounds

  1. 95% success
    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% success
    Inspect sub-exceptions:
    
    except ExceptionGroup as eg:
        for exc in eg.exceptions:
            logger.error('task failed', exc_info=exc)
  3. 85% success
    For libraries that don't support except*, unwrap manually:
    
    def unwrap(eg): return eg.exceptions[0] if len(eg.exceptions) == 1 else eg

Dead Ends

Common approaches that don't work:

  1. 90% fail

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

  2. 70% fail

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

  3. 95% fail

    Touches private state; unrelated to exception wrapping.