Search code examples
node.jsmongodbes6-promise

Node Promise rejection does not enter catch


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.


Solution

  • I think the problem is here:

    return Dashboard.findByIdAndRemove(id).exec((err, dashboard) => {
    

    Usually when you use promise you don't pass a callback. Try to change it to

    deleteDashboard = (id) => {
      return Dashboard.findByIdAndRemove(id).exec()
      .then(dashboard => {
        if (dashboard === null) return Promise.reject({ status: 404, message: 'not found' });
        return dashboard;
      })
      .catch(err => {
        return errorHandler.handle('dashboardService', err);
      })
    };
    

    I tried to keep most the code as it is. Just changed the callback for a promise, and the error handle for a catch.