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

其他格式: JSON · Markdown 中文 · English
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).

generic

解决方案

  1. 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)
  2. 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

无效尝试

常见但无效的做法:

  1. Removing all handlers and adding only one 50% 失败

    May lose custom error responses.

  2. Using different exception classes 60% 失败

    Doesn't solve duplicate registration.