N
Neon15mo ago
like-gold

Is the `DatabaseError` class from `@

Is the DatabaseError class from @neondatabase/serverless the same as PostgresError from the postgres package? Reason I'm asking is because I'm implementing errorhandling, and I want to type narrow the error type that is thrown when violating something like unique constraints forexample
3 Replies
deep-jade
deep-jade15mo ago
My CF worker is not happy about using the PostgresError class Essentially, can I do something like the following, where I have a recursive function to make sure that we are generating and inserting the verification code even if we have a unique violation
export default async function generateEmailVerificationCode(
user: User,
db: NeonDBWithSchemas | NeonDBWebSocketWithSchemas,
) {
const code = generateRandomString(6, alphabet('0-9'));
try {
await db
.delete(EmailVerificationCodeTable)
.where(eq(EmailVerificationCodeTable.userId, user.id));

await db.insert(EmailVerificationCodeTable).values({
userId: user.id,
code,
email: user.email,
expiresAt: createDate(new TimeSpan(15, 'm')), // 15 minutes
});

return code;
} catch (error) {
if (error instanceof DatabaseError && error.code === '23505') {
return generateEmailVerificationCode(user, db);
} else {
throw error;
}
}
}
export default async function generateEmailVerificationCode(
user: User,
db: NeonDBWithSchemas | NeonDBWebSocketWithSchemas,
) {
const code = generateRandomString(6, alphabet('0-9'));
try {
await db
.delete(EmailVerificationCodeTable)
.where(eq(EmailVerificationCodeTable.userId, user.id));

await db.insert(EmailVerificationCodeTable).values({
userId: user.id,
code,
email: user.email,
expiresAt: createDate(new TimeSpan(15, 'm')), // 15 minutes
});

return code;
} catch (error) {
if (error instanceof DatabaseError && error.code === '23505') {
return generateEmailVerificationCode(user, db);
} else {
throw error;
}
}
}
ambitious-aqua
ambitious-aqua15mo ago
Not sure. Reading the source code would be your best bet. It is open source on GitHub
deep-jade
deep-jade15mo ago
I tested it out in the meantime, seems to be the same thing, I'm getting the expected errors

Did you find this page helpful?