python runtime_error ai_generated true

任务异常从未被获取 future: <Task finished name='Task-5' coro=<fetch() done, defined at app.py:42> exception=ValueError('bad payload')>

Task exception was never retrieved future: <Task finished name='Task-5' coro=<fetch() done, defined at app.py:42> exception=ValueError('bad payload')>

ID: python/asyncio-task-exception-was-never-retrieved

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

版本兼容性

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

根因分析

使用 asyncio.create_task() 创建的任务抛出异常,但无人 await 该任务或调用 task.exception(),导致异常在垃圾回收时以警告形式记录。

English

A task created with asyncio.create_task() raised an exception, but nobody awaited the task or called task.exception(), so the exception is logged as a warning at garbage collection.

generic

解决方案

  1. 90% 成功率
    tasks = [asyncio.create_task(fetch(u)) for u in urls]
    results = await asyncio.gather(*tasks, return_exceptions=True)
    for r in results:
        if isinstance(r, Exception):
            logging.exception('task failed', exc_info=r)
  2. 87% 成功率
    def _on_done(t: asyncio.Task):
        if not t.cancelled() and t.exception():
            logging.error('task error', exc_info=t.exception())
    
    t = asyncio.create_task(fetch(u))
    t.add_done_callback(_on_done)

无效尝试

常见但无效的做法:

  1. 85% 失败

    Hides the symptom but the task still fails silently and the error is lost.

  2. 80% 失败

    Swallows real errors and produces no diagnostic; debugging becomes impossible.