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:
parent
cadcf753a7
commit
8fb7771223
3 changed files with 33 additions and 21 deletions
|
|
@ -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 };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue