How to properly handle/distinguish between errors

I'm using Drizzle ORM with a postgres. I'd like to distinguish between certain errors that occur when inserting / querying the database. In my current case, I would like to know specifically when my insertion fails as a result of a user not existing in the database. (See the comments in the catch block in the following example)
/**
*
* @param targetID the ID of the user to receive the friend request
*/
async sendUserFriendRequest(targetID: string): Promise<boolean> {
try {
await db
.insert(friends)
.values({
user1_ID: this.userID,
user2_ID: targetID,
status: "pending",
})
.onConflictDoNothing({ target: [friends.user1_ID, friends.user2_ID] });

log("social").debug(
`user ${this.userID} sent friend request to user ${targetID}`,
);
} catch (e) {
// if e is caused by targetID user not existing
// return false
// else
log("social").error(
`user '${this.userID}' failed to send friend request to user '${targetID}' %o`,
e,
);
return false;
}

return true;
}
/**
*
* @param targetID the ID of the user to receive the friend request
*/
async sendUserFriendRequest(targetID: string): Promise<boolean> {
try {
await db
.insert(friends)
.values({
user1_ID: this.userID,
user2_ID: targetID,
status: "pending",
})
.onConflictDoNothing({ target: [friends.user1_ID, friends.user2_ID] });

log("social").debug(
`user ${this.userID} sent friend request to user ${targetID}`,
);
} catch (e) {
// if e is caused by targetID user not existing
// return false
// else
log("social").error(
`user '${this.userID}' failed to send friend request to user '${targetID}' %o`,
e,
);
return false;
}

return true;
}
The error I get when a user does not exist is like so:
{
[message]: 'insert or update on table "friends" violates foreign key constraint "friends_user2_user_id_fk"',
length: 256,
name: 'error',
severity: 'ERROR',
code: '23503',
detail: 'Key (user2)=(hi) is not present in table "user".',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'public',
table: 'friends',
column: undefined,
dataType: undefined,
constraint: 'friends_user2_user_id_fk',
file: 'ri_triggers.c',
line: '2619',
routine: 'ri_ReportViolation'
}
{
[message]: 'insert or update on table "friends" violates foreign key constraint "friends_user2_user_id_fk"',
length: 256,
name: 'error',
severity: 'ERROR',
code: '23503',
detail: 'Key (user2)=(hi) is not present in table "user".',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'public',
table: 'friends',
column: undefined,
dataType: undefined,
constraint: 'friends_user2_user_id_fk',
file: 'ri_triggers.c',
line: '2619',
routine: 'ri_ReportViolation'
}
What is the proper / best way to differentiate between causes of errors while using drizzle?
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server