Skip to content

python.fastapi.exception_handler

Stability Medium

Detects FastAPI apps without proper exception handlers.

Missing exception handlers:

  • 500 errors exposed — Internal details leak to users
  • Poor UX — Generic error messages confuse users
  • No logging — Errors go untracked
# ❌ Before (no exception handler)
app = FastAPI()
@app.get("/users/{id}")
async def get_user(id: int):
return await db.get_user(id) # Unhandled errors!
# ✅ After (with exception handlers)
from fastapi import Request
from fastapi.responses import JSONResponse
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
logger.error("Unhandled error", exc_info=exc)
return JSONResponse(
status_code=500,
content={"detail": "Internal server error"}
)
@app.exception_handler(ValueError)
async def value_error_handler(request: Request, exc: ValueError):
return JSONResponse(
status_code=400,
content={"detail": str(exc)}
)
  • Missing @app.exception_handler
  • No fallback exception handler
  • Unstructured error responses