Skip to content

Instantly share code, notes, and snippets.

@ryantbrown
Last active June 14, 2025 23:49
Show Gist options
  • Save ryantbrown/78e3e12f9f70fc90c70b966cf67541d0 to your computer and use it in GitHub Desktop.
Save ryantbrown/78e3e12f9f70fc90c70b966cf67541d0 to your computer and use it in GitHub Desktop.
TypeScript Postgres Error Handling
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