Add withDb() helper for graceful DB error handling

Shared withDb() wrapper in @trails-cool/db catches database
connection errors and throws a 503 Response instead of crashing
the server. Re-throws React Router responses (redirects, data()).

Applied to Planner session routes — replaces manual try/catch.
Any route can use withDb(() => ...) for automatic 503 on DB failure.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ullrich Schäfer 2026-03-24 23:39:33 +01:00
parent cadcf753a7
commit 8fb7771223
No known key found for this signature in database
GPG key ID: A32FF691A0F752D9
3 changed files with 33 additions and 21 deletions

View file

@ -14,4 +14,28 @@ export function createDb(connectionString?: string) {
export type Database = ReturnType<typeof createDb>;
/**
* Wraps a route handler (loader/action) to catch database errors
* and return a 503 Service Unavailable instead of crashing.
*/
export function withDb<T>(handler: () => Promise<T>): Promise<T> {
return handler().catch((error) => {
if (error instanceof Response) throw error; // Re-throw React Router responses (redirects, data())
const message = error instanceof Error ? error.message : "Unknown error";
if (
message.includes("connect") ||
message.includes("ECONNREFUSED") ||
message.includes("DrizzleQueryError") ||
message.includes("AggregateError") ||
message.includes("database")
) {
throw new Response(JSON.stringify({ error: "Database unavailable" }), {
status: 503,
headers: { "Content-Type": "application/json" },
});
}
throw error;
});
}
export { plannerSchema, journalSchema };