Actualmente estoy escribiendo un servidor de nodo back-end con una base de datos Postgresql donde intenté configurar una API de registro. Quiero poder detectar errores causados por violaciones de restricciones únicas. ¿Cómo puedo hacer eso?
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; }) }Entonces, como no he encontrado ninguna respuesta a esto, creo que puedo compartir la mía.
Cada error en Postgresql tiene un código de error que se puede encontrar en: https://www.postgresql.org/docs/12/errcodes-appendix.html
Si observa el error que obtiene cuando hay una violación de clave única, puede notar que el código es "23505".
Simplemente agregue una marca en su bloque catch para ver si el error tiene un código de "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; }) }