Add graceful error handling for db-sync initialization
This commit is contained in:
parent
104e11f098
commit
631a0aa2a0
1 changed files with 23 additions and 0 deletions
23
main.py
23
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):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue