0

I'm wondering what the best way to handle errors in long functions with promises are?

My function:

module.exports = function(data) {
  var deferred = Q.defer();
  var config = {};


  fs.readdir(path, function(err, files) {
    if (err) {
      deferred.reject(new Error(err));
    }
    var infoPath = false;

    files.forEach(function(filename) {
      if (filename.indexOf('.info') !== -1) {
        infoPath = path + '/' + filename;
        config['moduleName'] = filename.replace('.info', '');
      }
    });

    if (!infoPath) {
      deferred.reject(new Error('Did not find .info-file'));
    }

    if (files.indexOf(config['moduleName'] + '.module') > -1) {
      config.type = 'Modules';
    }
    else {
      deferred.reject(new Error('Unknown project type'));
    }

    // Parse the info file.
    fs.readFile(infoPath, function (err, content) {
      if (err) {
        deferred.reject(new Error(err));
      }

      data.config = config;
      data.infoContent = content.toString();

      deferred.resolve(data); 
    });
  });
  return deferred.promise;
};

As far as I understand it this is the way to use Q.defer. But if a error is thrown, I don't want/need it to try the rest of function. Am I missing something or are there a better way to do this?

andeersg
  • 1,505
  • 2
  • 13
  • 24
  • 1
    Have a look [here](http://stackoverflow.com/q/31933675/1048572). Try to promisify on the lowest level, i.e. make `readdir`/`readfile` functions that return promises (and don't have any additional logic), then use only those and [avoid the `Promise` constructor](http://stackoverflow.com/q/23803743/1048572) elsewhere. – Bergi Jan 30 '16 at 23:56
  • Thank you Bergi, that really explained my problem/question :) – andeersg Feb 01 '16 at 07:33

1 Answers1

1

Rejecting a promise doesn't miraculously stop the function from executing the rest of its code. So after rejecting, you should return from the function:

if (err) {
  deferred.reject(new Error(err));
  return;
}

Or shorter:

if (err) {
  return deferred.reject(new Error(err));
}
robertklep
  • 198,204
  • 35
  • 394
  • 381