feat: enhance error handling for database and API connections with detailed descriptions

This commit is contained in:
sai80082 committed 2026-05-05 14:41:36 +05:30
1 parent b8dee930b5
commit b2aa043ab6
2 files changed
+67 -3

No files matched your search

+45 -1
View File
@@ -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<typeof schema>) => {
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<typeof schema>) => {
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");
}
}
+22 -2
View File
@@ -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,
});
})