1

I seem to be struggling to handle any database errors within my app. I have a simple query that updates a users password

// Update Users Password
async function updatePassword(password, id) {
  const client = await pool.connect();
  const sql = format('UPDATE users SET password = $1 WHERE id = $2');
  try {
    await pool.query(sql, [password, id]);
  } catch (e) {
    console.error('Error Occurred', e);
    client.release();
  }
}

Server side i have this in my routes.js

const newPassword = bcrypt.hashSync(req.body.update_password, 10);
try {
  await queries.updatePassword(newPassword, req.body.user_id);
  res.status(200).send({ result: 'Password Updated Successfully' });
} catch (e) {
  res.status(400).send({ result: 'Oops, please try again' });
}

If there are no database errors then this works as expected, but if for example i supply a string as my id (forcing the error) then I get this error printed to the console as expected

Error Occurred { error: invalid input syntax for integer: "string"

but still res.status(200).send({ result: 'Password Updated Successfully' }); is sent.

Logged as

POST /update_password 200

How can I capture the error as I thought I was being that its in the try/catch block ?

Thanks

1 Answer 1

2

Your problem is irrelevant of the libraries that you use. You simply misuse async/await error reporting.

Your function updatePassword does not re-throw the error, thus swallowing it. Have it re-throw the error, and the error will be reported correctly:

catch (e) {
    console.error('Error Occurred', e);
    throw e;
  }

As for the database code, it also looks bad - you allocate a new connection inside the method, but release it only inside catch, which means the connection will remain occupied when no error thrown, thus quickly depleting the connection pool.

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

1 Comment

Thank you for your answer, have also refactored my database connections

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.