gpt4 book ai didi

node.js - 如何捕获 Node 中的 psql 错误?

转载 作者:行者123 更新时间:2023-12-05 02:51:59 24 4
gpt4 key购买 nike

我目前正在编写一个带有 Postgresql 数据库的后端 Node 服务器,我试图在其中设置注册 API。我希望能够捕获由违反唯一约束引起的错误。我该怎么做?

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;
})
}

最佳答案

既然我还没有找到任何答案,我想我可以分享我的答案。

Postgresql 中的每个错误都有一个错误代码,可以在以下位置找到: https://www.postgresql.org/docs/12/errcodes-appendix.html

如果您查看唯一 key 违规时收到的错误,您可能会注意到代码是“23505”。

只需在您的 catch block 中添加检查以查看错误代码是否为“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;
})
}

关于node.js - 如何捕获 Node 中的 psql 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62855984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com