python
config_error
ai_generated
true
RuntimeError: Multiple exception handlers registered for the same exception type.
ID: python/starlette-runtime-error-multiple-exception-handlers
80%Fix Rate
81%Confidence
0Evidence
2024-11-20First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Two or more exception handlers are added for the same exception class (e.g., HTTPException).
generic中文
为同一个异常类(例如 HTTPException)添加了两个或多个异常处理程序。
Workarounds
-
90% success 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% success 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
Dead Ends
Common approaches that don't work:
-
Removing all handlers and adding only one
50% fail
May lose custom error responses.
-
Using different exception classes
60% fail
Doesn't solve duplicate registration.