python runtime_error ai_generated true

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

ID: python/starlette-lifespan-startup-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-12-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Skips DB connection and other required startup logic.

  2. 80% fail

    Server starts in a broken state with missing resources.