0

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],
     });
  });
};
2
  • 1
    which json object? please add your code to the question. Commented Mar 2, 2022 at 13:48
  • I edited the question. I just want to know how to check the UNIQUE constraint in an if/else condition so that if the client puts an email that's already in the database, they get an error or message saying 'Email already taken' Commented Mar 2, 2022 at 14:02

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.