diff --git a/main.py b/main.py index 92e000d..f23e701 100644 --- a/main.py +++ b/main.py @@ -29,6 +29,7 @@ from fastapi import FastAPI, Request, HTTPException, Query, Header, Depends from fastapi.responses import JSONResponse from pydantic import BaseModel import asyncpg +from asyncpg.exceptions import UndefinedTableError, PostgresError import redis.asyncio as redis # Configure logging @@ -109,6 +110,28 @@ app = FastAPI( ) +# ============ Exception Handlers ============ + +@app.exception_handler(UndefinedTableError) +async def handle_undefined_table(request: Request, exc: UndefinedTableError): + """Handle missing tables (db-sync still initializing).""" + logger.warning(f"Database not ready: {exc}") + return JSONResponse( + status_code=503, + content={"error": "db_sync_not_ready", "message": "Database sync in progress. Tables not yet created."} + ) + + +@app.exception_handler(PostgresError) +async def handle_postgres_error(request: Request, exc: PostgresError): + """Handle general postgres errors.""" + logger.error(f"Database error: {exc}") + return JSONResponse( + status_code=503, + content={"error": "database_error", "message": str(exc)} + ) + + # ============ Models ============ class APIKeyCreate(BaseModel):