python
config_error
ai_generated
true
RuntimeError: 为同一异常类型注册了多个异常处理程序。
RuntimeError: Multiple exception handlers registered for the same exception type.
ID: python/starlette-runtime-error-multiple-exception-handlers
80%修复率
81%置信度
0证据数
2024-11-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
为同一个异常类(例如 HTTPException)添加了两个或多个异常处理程序。
English
Two or more exception handlers are added for the same exception class (e.g., HTTPException).
解决方案
-
90% 成功率 Consolidate handlers into one
from starlette.exceptions import HTTPException from starlette.responses import JSONResponse async def custom_handler(request, exc): return JSONResponse({'error': str(exc.detail)}, status_code=exc.status_code) app.add_exception_handler(HTTPException, custom_handler) -
85% 成功率 Use middleware instead of multiple handlers
from starlette.middleware.base import BaseHTTPMiddleware class ErrorMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): try: response = await call_next(request) except HTTPException as exc: return JSONResponse({'error': exc.detail}, status_code=exc.status_code) return response
无效尝试
常见但无效的做法:
-
Removing all handlers and adding only one
50% 失败
May lose custom error responses.
-
Using different exception classes
60% 失败
Doesn't solve duplicate registration.