Add graceful error handling for db-sync initialization

This commit is contained in:
Kayos 2026-03-18 11:47:03 -07:00
parent 104e11f098
commit 631a0aa2a0

23
main.py
View file

@ -29,6 +29,7 @@ from fastapi import FastAPI, Request, HTTPException, Query, Header, Depends
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from pydantic import BaseModel from pydantic import BaseModel
import asyncpg import asyncpg
from asyncpg.exceptions import UndefinedTableError, PostgresError
import redis.asyncio as redis import redis.asyncio as redis
# Configure logging # 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 ============ # ============ Models ============
class APIKeyCreate(BaseModel): class APIKeyCreate(BaseModel):