I have a method calling findByIdAndRemove on a mongoDB. In case I don't find the id and therefore can't delete it from the DB, I want to throw an error.
Delete dashboard function:
deleteDashboard = (id) => {
return Dashboard.findByIdAndRemove(id).exec((err, dashboard) => {
if (err) return errorHandler.handle('dashboardService', err);
if (dashboard === null) return Promise.reject({ status: 404, message: 'not found' });
return Promise.resolve(dashboard);
});
};
Function call:
return dashboardService.deleteDashboard(id)
.then(dashboard => res.status(200).json(dashboard))
.catch(error => res.status(error.status).json(error));
I don't understand why calling dashboardService.deleteDashboard with an id that isn't in the database, doesn't enter the catch. While debugging, I checked that is enters the if(dashboard === null) condition and thus calls Promise.reject(), but then it enters the then instead of the catch.