[英]Check for UNIQUE constraint in Node-Postgres
我在我的表的“電子郵件”列上設置了 UNIQUE 約束,現在在我使用 Node-Postgres (pg) 的 Express API 中,我想確保用戶在發布學生時輸入的 email 不是沒有重復。
我的問題是如何顯示“電子郵件已收到?”之類的回復。 在我的 JSON object 中,當該約束被違反時?
const createStudent = (req, res) => {
const { name, email, age, dob } = req.body;
pool.query(insertStudent, [name, email, age, dob], (error, results) => {
if (error) throw error;
res.status(201).json({
message: `Student Created Successfully!`,
student: results.rows[0],
});
});
};
您可以在此處找到 postgresql 返回的錯誤代碼:
https://www.postgresql.org/docs/current/errcodes-appendix.html
unique_violation
的錯誤代碼是23505 。 此外,錯誤 object 具有constraint
字段,報告違反約束的名稱。 所以
pool.query(..., (error, results) => {
if (error.code == 23505 && error.constraint == 'your_unique_cons_name') {
// handle error
}
});
編輯:這是完整的代碼,我不知道你到底從哪里得到這些錯誤,也許張貼你的代碼和完整的錯誤信息。
if (error != null && error.code == 23505 && error.constraint == 'your_unique_cons_name') {
res.status(418).json({
message: `email taken!`,
});
}
else {
res.status(201).json({
message: `Student Created Successfully!`,
student: results.rows[0],
});
}
我設法通過使用async/await
和try/catch
並在 catch 語句中提供錯誤邏輯來解決問題。
這現在按預期工作:
const createStudent = async (req, res, next) => {
const { name, email, age, dob} = req.body;
try {
const create = await pool.query(insertStudent, [
name,
email,
age,
dob,
]);
res
.status(201)
.json({ message: "Student Created Successfully!", user: create.rows[0] });
} catch (err) {
// If UNIQUE constraint is violated
if (err.code == "23505") {
console.error(err.message);
const error = new Error("Email Already Exists!");
error.status = 400;
next(error);
} else {
console.error(err.message);
const error = new Error("Something Went Wrong!");
error.status = 500;
next(error);
}
}
};
我使用了 Express Error Handling 中間件,但其他方法也可以。
感謝@boran 的大力幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.