From 74a70e99ca7a32850dc4daa0a4878a9a5b65e2e0 Mon Sep 17 00:00:00 2001 From: rizky Date: Wed, 10 Sep 2025 09:07:03 +0700 Subject: [PATCH] fix database connection error handling to prevent app crashes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add proper error handling in database connection attempts - Set g.db to null when connection fails to prevent subsequent crashes - Add null check in execQuery to throw meaningful error when DB unavailable - Improve API endpoint to return 503 status when database is unavailable - Enhanced logging for better debugging of connection issues 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- pkgs/api/_dbs.ts | 5 ++++- pkgs/index.ts | 4 +++- pkgs/utils/prisma.ts | 3 ++- pkgs/utils/query.ts | 4 ++++ 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/pkgs/api/_dbs.ts b/pkgs/api/_dbs.ts index cdceee5..14ef109 100644 --- a/pkgs/api/_dbs.ts +++ b/pkgs/api/_dbs.ts @@ -10,7 +10,7 @@ export const _ = { async api() { const ctx = apiContext(this); const { req, res } = ctx; - if (typeof g.db !== "undefined") { + if (typeof g.db !== "undefined" && g.db !== null) { if (req.params._ === "check") { return { mode: "encrypted" }; } @@ -30,6 +30,9 @@ export const _ = { res.sendStatus(500); res.send('{status: "unauthorized"}'); } + } else { + res.status(503); + res.send('{"status": "database_unavailable", "message": "Database connection not available"}'); } }, }; diff --git a/pkgs/index.ts b/pkgs/index.ts index b68fc42..334769c 100644 --- a/pkgs/index.ts +++ b/pkgs/index.ts @@ -65,8 +65,10 @@ await createLogger(); if (g.db) { try { await g.db.$connect(); + g.log.info("Database connected successfully"); } catch (e) { - console.error(e); + g.log.error("Failed to connect to database:", e); + g.db = null; } } diff --git a/pkgs/utils/prisma.ts b/pkgs/utils/prisma.ts index 44cc793..bab6891 100644 --- a/pkgs/utils/prisma.ts +++ b/pkgs/utils/prisma.ts @@ -28,7 +28,8 @@ export const preparePrisma = async () => { }) as Upsert, }; } catch (e) { - console.log("Prisma not initialized", e); + console.error("Failed to initialize Prisma:", e); + g.db = null; } } diff --git a/pkgs/utils/query.ts b/pkgs/utils/query.ts index fab9009..39e0a6c 100644 --- a/pkgs/utils/query.ts +++ b/pkgs/utils/query.ts @@ -13,6 +13,10 @@ export type DBArg = { }; export const execQuery = async (args: DBArg, prisma: any) => { + if (!prisma) { + throw new Error("Database connection not available"); + } + const { table, action, params } = args; if (action === "batch_upsert") {