I have put a UNIQUE constraint on the "email" column of my table and now in my Express API which is using Node-Postgres (pg), I want to make sure than the email that the user puts in when POSTing a student, isn't duplicated.
My question is that how can I show a response like "Email already taken?" in my JSON object when that constraint gets violated?
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],
});
});
};
You can find error codes returned by postgresql here:
https://www.postgresql.org/docs/current/errcodes-appendix.html
Error code of unique_violation
is 23505 . Additionally error object has constraint
field that reports name of the constraint being violated. Therefore
pool.query(..., (error, results) => {
if (error.code == 23505 && error.constraint == 'your_unique_cons_name') {
// handle error
}
});
Edit: Here is the full code, I don't know where exactly are you getting these errors, maybe post your code and full error messages.
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],
});
}
I managed to fix the problem by using async/await
and try/catch
and providing the error logic in the catch statement.
This now works as expected:
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);
}
}
};
I have used Express Error Handling middleware but the other way work as well.
Thanks to @boran for his great help!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.