# FastAPI HTTP 异常：500 内部服务器错误

- **ID:** `python/fastapi-http-exception-handler-missing`
- **领域:** python
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

FastAPI 应用未处理未捕获的异常，导致返回 500 错误

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.9 | active | — | — |
| 3.10 | active | — | — |

## 解决方案

1. **添加全局异常处理器** (95% 成功率)
   ```
   @app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    return JSONResponse(status_code=500, content={'detail': '内部错误'})
   ```
2. **使用中间件捕获未处理异常** (90% 成功率)
   ```
   @app.middleware('http')
async def catch_exceptions(request, call_next):
    try:
        return await call_next(request)
    except Exception:
        return JSONResponse(status_code=500, content={'detail': '错误'})
   ```

## 无效尝试

- **在路径操作中使用 try-except 但不记录日志** — 错误被隐藏，难以调试 (70% 失败率)
- **返回空响应而不提供错误信息** — 客户端无法知道错误原因 (60% 失败率)
