Bubble Up Error From Promise Functions

345 views Asked by At

I am trying to get used to using Promises.

However, I am struggling to get an error throw in a sub-function to bubble up to the main function.

I use Senecajs for all my modules, like so:

// resend-invite.js
module.exports = function(options) {
  const Promise = require('bluebird'),
        seneca = this,
        act = Promise.promisify(seneca.act, {context: seneca});

  this.add({role:'project-actions', cmd: 'resend-invite'}, function( msg, done ) {
    return findProject()
    .then(function(project) {
      if ( !project.userHasAdminAccess( msg.user_id ) ) {
        throw Error( 'User does not have admin access.' );
      }

      // makes it here...
      return act( { role: "user-repository", cmd: "get-referral-user", user: { email: msg.email } } );
    })
    .then(function(referral_user) {
      // doesn't make it here :(
      var referral_name = referral_user.first_name + " " + referral_user.last_name;

      return anotherFunction();
    })
    .then(function(mail_info) {
      done(null, mail_info);
    })
    .catch(function(err) {
      // doesn't make it here :(
      done(err);
    })
  });
}

And like this:

// get-referral-user.js
module.exports = function(options) {
  const Promise = require('bluebird'),
        seneca = this,
        User = require('app/models/user');

  this.add({role:'user-repository', cmd: 'get-referral-user'}, function( msg, done ) {
    return User.findOne(msg.user).exec()
    .then(function(user) {
      var referral_user_id;

      if (user == null) {
        throw Error("User wasn't found.");
      }

      referral_user_id = user.referral_user_id;

      return User.findById(referral_user_id).exec()
    })
    .then(function(user) {
      done(null, user.toObject());
    })
    .catch(function(err) {
      // gets to this err handler
      done(err);
    })
  });
}

However, when there is an error in get-referral-user.js, it is caught by the get-referral-user.js .catch block, but the error is not caught by thr resend-invite.js catch block.

How do I get the resend-invite.js code to detect that a sub-function (act( { role: "user-repository", cmd: "get-referral-user", user: { email: msg.email } } ) in this case) has an error and needs to be handled.

Here are the parts of the error that is produced in my console that could be helpful:

Seneca Fatal Error

Message: seneca: Action cmd:get-referral-user,role:user-repository failed: User wasn't found..

..

ALL ERRORS FATAL: action called with argument fatal$:true (probably a plugin init error, or using a plugin seneca instance)

Any help is greatly appreciated. Thank you.

0

There are 0 answers