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

- **ID:** `python/starlette-lifespan-startup-error`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

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)
   ```

## 无效尝试

- **** — Skips DB connection and other required startup logic. (85% 失败率)
- **** — Server starts in a broken state with missing resources. (80% 失败率)
