Last active
June 14, 2025 23:49
-
-
Save ryantbrown/78e3e12f9f70fc90c70b966cf67541d0 to your computer and use it in GitHub Desktop.
TypeScript Postgres Error Handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { DatabaseError } from "pg"; | |
import { DatabaseErrorCode } from "./errors"; | |
/** | |
* Higher order function with fine-grained error handling. | |
*/ | |
export async function withErrorHandling<T>( | |
fn: () => Promise<T>, | |
onError: Record<string, (error: PgDatabaseError) => void>, | |
) { | |
try { | |
return await fn(); | |
} catch (error) { | |
if (!(error instanceof PgDatabaseError)) { | |
throw error; | |
} | |
onError[error.code as string]?.(error); | |
} | |
} | |
export async function createUser(params: typeof users.$inferInsert) { | |
return withErrorHandling( | |
async () => { | |
const [created] = await db | |
.insert(users) | |
.values(params) | |
.returning(); | |
if (!created) { | |
throw new ResourceCreationError("user"); | |
} | |
return created; | |
}, | |
{ | |
[DatabaseErrorCode.UniqueViolation]: (error) => { | |
throw new ResourceConflictError("That email address is taken", error); | |
}, | |
}, | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment