From b2aa043ab65b21b1a85a41ea94a1feb576cff679 Mon Sep 17 00:00:00 2001 From: sai80082 Date: Tue, 5 May 2026 14:41:36 +0530 Subject: [PATCH] feat: enhance error handling for database and API connections with detailed descriptions --- src/config/db.ts | 46 +++++++++++++++++++++++++- src/handlers/serverUtils/user.utils.ts | 24 ++++++++++++-- 2 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/config/db.ts b/src/config/db.ts index f39e4e1..c3b1e0d 100644 --- a/src/config/db.ts +++ b/src/config/db.ts @@ -26,6 +26,40 @@ class DatabaseConnectionError extends Error { this.error = error; } } + +const getRootCause = (error: any): any => { + let current = error; + while (current?.cause) current = current.cause; + return current; +}; + +const describePgError = (error: any): string => { + const root = getRootCause(error); + const target = `${ENV.DB_HOST || '?'}:${ENV.DB_PORT || '?'}`; + const code = root?.code as string | undefined; + + switch (code) { + case 'ENOTFOUND': + return `Cannot resolve database host "${ENV.DB_HOST}". Check DB_HOST and that the power-tools container is on the same Docker network as the Immich Postgres container (use the container name, e.g. "immich_postgres").`; + case 'ECONNREFUSED': + return `Connection refused at ${target}. The host is reachable but nothing is listening on that port — check DB_PORT and that Postgres is running.`; + case 'ETIMEDOUT': + case 'EHOSTUNREACH': + case 'ENETUNREACH': + return `Cannot reach ${target} (${code}). Likely a network/firewall issue or the wrong DB_HOST for this container.`; + case '28P01': + return `Password authentication failed for user "${ENV.DB_USERNAME}". Check DB_PASSWORD (and ensure no extra quotes/spaces in .env).`; + case '28000': + return `Authentication failed for user "${ENV.DB_USERNAME}" at ${target}. Check DB_USERNAME and pg_hba rules.`; + case '3D000': + return `Database "${ENV.DB_DATABASE_NAME}" does not exist on ${target}. Check DB_DATABASE_NAME.`; + case '57P03': + return `Postgres at ${target} is starting up and not yet ready to accept connections.`; + default: + return `${root?.message || error?.message || 'Unknown error'}${code ? ` (code: ${code})` : ''} — target ${target}, user "${ENV.DB_USERNAME}", db "${ENV.DB_DATABASE_NAME}".`; + } +}; + export const connectDB = async (db: NodePgDatabase) => { try { const missingKeys = findMissingKeys(ENV, ['DB_USERNAME', 'DB_PASSWORD', 'DB_HOST', 'DB_PORT', 'DB_DATABASE_NAME']); @@ -38,7 +72,17 @@ export const connectDB = async (db: NodePgDatabase) => { return await db.execute(sql`SELECT 1`); // Execute a simple query } } catch (error: any) { - throw new DatabaseConnectionError(error.message, "Database connection failed"); + if (error instanceof APIError) throw error; + const root = getRootCause(error); + console.error('[db] connection failed:', { + code: root?.code, + message: root?.message, + host: ENV.DB_HOST, + port: ENV.DB_PORT, + user: ENV.DB_USERNAME, + database: ENV.DB_DATABASE_NAME, + }); + throw new DatabaseConnectionError(describePgError(error), "Database connection failed"); } } diff --git a/src/handlers/serverUtils/user.utils.ts b/src/handlers/serverUtils/user.utils.ts index 6756e1a..93282e0 100644 --- a/src/handlers/serverUtils/user.utils.ts +++ b/src/handlers/serverUtils/user.utils.ts @@ -6,6 +6,24 @@ import { getCookie } from "@/lib/cookie" import { NextApiRequest } from "next" +const describeFetchError = (error: any, url: string): string => { + let current = error; + while (current?.cause) current = current.cause; + const code = current?.code as string | undefined; + switch (code) { + case 'ENOTFOUND': + return `Cannot resolve host for ${url}. Check IMMICH_URL — from inside this container, an IP on the host network may not be reachable; prefer the Immich container name (e.g. http://immich_server:2283).`; + case 'ECONNREFUSED': + return `Connection refused at ${url}. Check that the Immich server is running and that IMMICH_URL points to its internal port (default 2283).`; + case 'ETIMEDOUT': + case 'EHOSTUNREACH': + case 'ENETUNREACH': + return `Cannot reach Immich API at ${url} (${code}). Likely the power-tools container is not on the same network as the Immich server.`; + default: + return `Failed to connect to Immich API at ${url}: ${current?.message || error?.message || 'Unknown error'}${code ? ` (${code})` : ''}`; + } +}; + export const getCurrentUserFromAPIKey = () => { if (!ENV.IMMICH_URL || !ENV.IMMICH_API_KEY) return null; @@ -32,8 +50,9 @@ export const getCurrentUserFromAPIKey = () => { if (error instanceof APIError) { throw error; } + console.error('[immich-api] connect failed:', { url: ENV.IMMICH_URL, message: error?.message, cause: error?.cause }); throw new APIError({ - message: "Failed to connect to Immich API: " + ENV.IMMICH_URL, + message: describeFetchError(error, ENV.IMMICH_URL), status: 500, }); }) @@ -51,8 +70,9 @@ export const getCurrentUserFromAccessToken = (token: string) => { } return null }).catch((error) => { + console.error('[immich-api] connect failed:', { url: ENV.IMMICH_URL, message: error?.message, cause: error?.cause }); throw new APIError({ - message: "Failed to connect to Immich API: " + ENV.IMMICH_URL, + message: describeFetchError(error, ENV.IMMICH_URL), status: 500, }); })