python runtime_error ai_generated true

RuntimeError: 任务异常未被获取 future: <Task finished ...> ... lifespan 启动期间出错

RuntimeError: Task exception was never retrieved future: <Task finished ...> ... Error during lifespan startup

ID: python/starlette-lifespan-startup-error

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

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

在 lifespan 启动处理程序中抛出的异常阻止了 ASGI 服务器完成启动。

English

An exception raised inside the lifespan startup handler prevents the ASGI server from fully starting.

generic

解决方案

  1. 92% 成功率
    from contextlib import asynccontextmanager
    @asynccontextmanager
    async def lifespan(app):
        try:
            await init_db()
        except Exception:
            logger.exception('startup failed')
            raise
        yield
  2. 88% 成功率
    for _ in range(5):
        try: await init_db(); break
        except Exception: await asyncio.sleep(2)

无效尝试

常见但无效的做法:

  1. 85% 失败

    Skips DB connection and other required startup logic.

  2. 80% 失败

    Server starts in a broken state with missing resources.