python runtime_error ai_generated true

starlette.exceptions.HTTPException: 404: Not Found

ID: python/starlette-http-exception-status-code

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-07-21First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.37.x active — — —
0.40.x active — — —

Root Cause

A route or dependency explicitly raised HTTPException(404) or a router matched no path, and the exception was not handled by a custom handler.

generic

中文

某个路由或依赖显式抛出了 HTTPException(404),或路由器未匹配到任何路径,且异常未被自定义处理器捕获。

Workarounds

  1. 95% success
    @app.exception_handler(HTTPException)
    async def handler(request, exc):
        return JSONResponse({'detail': exc.detail}, status_code=exc.status_code)
  2. 90% success
    Register the handler on the specific router or app instance used in tests, not on a different app object.

Dead Ends

Common approaches that don't work:

  1. 80% fail

    HTTPException is handled by Starlette's HTTPException handler before generic Exception; order matters and generic handler may not fire.

  2. 70% fail

    Duplicates logic across every route and bypasses OpenAPI error docs.