python runtime_error ai_generated true

fastapi.HTTPException: 500 Internal Server Error: An internal error occurred

ID: python/fastapi-http-exception-custom

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

在端点函数中抛出了未捕获的异常,FastAPI 默认返回 500 错误。

generic

中文

在端点函数中抛出了未捕获的异常,FastAPI 默认返回 500 错误。

Workarounds

  1. 90% success
    @app.exception_handler(Exception)
    async def handle_exc(request, exc):
        return JSONResponse({'error': 'internal'}, status_code=500)
  2. 85% success
    try:
        ...
    except ValueError:
        raise HTTPException(400, 'bad value')

Dead Ends

Common approaches that don't work:

  1. 60% fail

    如果错误是系统性的,重试仍会失败。

  2. 50% fail

    关闭调试模式不会修复根本问题,只是隐藏错误信息。