From 631a0aa2a0a2ee795408487cdc0332e8da829b59 Mon Sep 17 00:00:00 2001 From: Kayos Date: Wed, 18 Mar 2026 11:47:03 -0700 Subject: [PATCH] Add graceful error handling for db-sync initialization --- main.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) 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):