I have a very common scenario where I need to check if the user already exists in database? if yes, then return back an error to the user saying username already exists. I am using mongoose and its findOne method:
exports.registerUser = async (req, res) => {
await userModel.findOne({'email': req.body.email}).exec().then((result) => {
//user is already present in the db
respondWithError(HttpStatus.BAD_REQUEST, "The user exists in the db")
}).catch(error => {
// user is not in the db - save
saveTheUserToDb(req)
res.render('home');
})
}
here is my respondWithError function:
const respondWithError = (httpStatus, message) => {
throw new BaseError(httpStatus, message)
}
and here is the BaseError
class BaseError extends Error {
constructor(httpStatus, message) {
super();
this.httpStatus = httpStatus
this.message = message
}
}
The issue is that when findOne(...).exex() comes back and promise is resolved respondWithError is called which leads the execution directly into catch block where the user is saved in the DB which obviously is not what is intended.
What is the right way of sending back an error when it has to be in the resolve of a promise?