# 运行时错误：生命周期协议错误：在'lifespan.startup.complete'之前收到了'lifespan.shutdown'

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

## 根因

ASGI服务器在启动完成前发送了关闭信号，通常是由于启动处理器中出现错误。

## 版本兼容性

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

## 解决方案

1. **Fix the error in the startup handler** (90% 成功率)
   ```
   @app.on_event('startup')
async def startup():
    try:
        # initialization code
    except Exception as e:
        print(f"Startup error: {e}")
   ```
2. **Use try-except in lifespan context manager** (85% 成功率)
   ```
   @asynccontextmanager
async def lifespan(app):
    try:
        await startup()
        yield
    finally:
        await shutdown()
   ```

## 无效尝试

- **Ignoring the error and restarting the server** — Error will recur if the startup handler still fails. (70% 失败率)
- **Removing the lifespan handler entirely** — Removes startup/shutdown functionality, but may hide important initialization. (60% 失败率)
