Expose DB connection error in /health response for debugging
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -13,10 +13,10 @@ def _params() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def check_db() -> bool:
|
||||
def check_db() -> tuple[bool, str]:
|
||||
try:
|
||||
conn = pymysql.connect(**_params())
|
||||
conn.close()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
return True, "ok"
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
|
||||
12
app/main.py
12
app/main.py
@@ -10,10 +10,11 @@ logger = logging.getLogger("pops")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
if check_db():
|
||||
ok, msg = check_db()
|
||||
if ok:
|
||||
logger.info("Database connection OK")
|
||||
else:
|
||||
logger.warning("Database unreachable — check MYSQL_* environment variables")
|
||||
logger.warning("Database unreachable: %s", msg)
|
||||
yield
|
||||
|
||||
|
||||
@@ -27,8 +28,9 @@ def root():
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
db_ok = check_db()
|
||||
ok, msg = check_db()
|
||||
return {
|
||||
"status": "ok" if db_ok else "degraded",
|
||||
"db": "connected" if db_ok else "unreachable",
|
||||
"status": "ok" if ok else "degraded",
|
||||
"db": "connected" if ok else "unreachable",
|
||||
"detail": msg,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user