python runtime_error ai_generated true

TypeError: 'HTTPException' object is not callable

ID: python/starlette-http-exception-not-callable

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

当在Starlette或FastAPI中将HTTPException实例(而非异常类)作为依赖项或中间件传递时,框架尝试调用它,导致类型错误。

generic

中文

在Starlette或FastAPI中,将HTTPException实例(而非异常类)作为依赖项或中间件传递时,框架会尝试调用它,从而引发类型错误。

Workarounds

  1. 95% success 使用Starlette的HTTPException类作为异常抛出,而非作为返回值
    from starlette.exceptions import HTTPException; raise HTTPException(status_code=404, detail='Not found')
  2. 90% success 在依赖项中返回Response对象替代异常实例
    from starlette.responses import JSONResponse; return JSONResponse(status_code=404, content={'detail': 'Not found'})

Dead Ends

Common approaches that don't work:

  1. 尝试将HTTPException作为函数导入并直接调用 70% fail

    HTTPException是类,不是函数,直接调用不会触发异常,但作为依赖项仍会出错。

  2. 在依赖项中使用raise HTTPException而不是return 60% fail

    在依赖项中raise会立即中断请求,但若返回实例则仍会引发错误。