Reputation: 365
I'm currently writing a backend node server with a Postgresql database where I've attempted to make a registration API set-up. I want to be able to catch errors that are caused by unique constraint violations. How can I do that?
function createMember(body, callBack){
// This function adds someone who is newly registered to the database.
var id;
var sql = 'INSERT INTO member (fname, lname, phone, email, age, gender) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id;';
db.query(sql, [body.fname, body.lname, body.phone, body.email, body.age, body.gender]).then(res => {
id = res.rows[0].id;
if (id) {
callBack(body);
console.log("New member with id: " + id);
}
}).catch(e => {
if (the error is a unique constraint violation){
console.log("\n ERROR! \n Individual with name: " + body.fname + " " + body.lname + " and phone #: " + body.phone + " is a duplicate member. \n");
callBack("Duplicate");
return;
}
console.log("\n \n ERROR! \n Individual with name: " + body.fname + " " + body.lname + " and phone #: " + body.phone + " could not be added. \n", e);
callBack(false);
return e;
})
}
Upvotes: 7
Views: 10519
Reputation: 365
So since I haven't found any answers to this, I think I can share mine.
Each error in Postgresql has an error code which can be found at: https://www.postgresql.org/docs/12/errcodes-appendix.html
If you look at the error you get when there is a unique key violation you may notice that the code is "23505".
Simply add a check in your catch block to see if the error has a code of "23505".
function createMember(body, callBack){
// This function adds someone who is newly registered to the database.
var id;
var sql = 'INSERT INTO member (fname, lname, phone, email, age, gender) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id;';
db.query(sql, [body.fname, body.lname, body.phone, body.email, body.age, body.gender]).then(res => {
id = res.rows[0].id;
if (id) {
callBack(body);
console.log("New member with id: " + id);
}
}).catch(e => {
if (e.code == '23505'){
console.log("\n ERROR! \n Individual with name: " + body.fname + " " + body.lname + " and phone #: " + body.phone + " is a duplicate member. \n");
callBack("Duplicate");
return;
}
console.log("\n \n ERROR! \n Individual with name: " + body.fname + " " + body.lname + " and phone #: " + body.phone + " cannot be added. \n", e);
callBack(false);
return e;
})
}
Upvotes: 11