繁体   English   中英

如何在节点中捕获 psql 错误?

[英]How do I catch psql errors in node?

我目前正在编写一个带有 Postgresql 数据库的后端节点服务器,我试图在其中进行注册 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;
  })
}

因此,由于我还没有找到任何答案,我想我可以分享我的。

Each error in Postgresql has an error code which can be found at: https://www.postgresql.org/docs/12/errcodes-appendix.html

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM