Aug
02

Catching JavaScript errors with Promises

posted on 02 August 2014 in programming with 0 Comments

Warning: Please consider that this post is over 2 years old and the content may no longer be relevant.

If your JS function needs to return a Promise but doesn’t do any asynchronous activity, you may be tempted to use the static Promise.resolve() function rather than instantiating a new Promise object. Be aware that doing this will change the way javascript errors are dealt with.

Using the static method means normal JavaScript error handling will take place and your Promise catch() function won’t be called. E.g.

var p = function() {
  throw 'new error';
  return Promise.resolve('hi');
};

p()
  .then(function(a) { console.log(a); })
  .catch(function(e) { console.error('there was an error'); });

Will result in seeing the error ‘new error’ logged by the console. The promise then / catch functions are never called. Whereas:

var p = function() {
  return new Promise(function(resolve, reject) {
    throw 'new error';
    resolve('hi');
  });
};

p()
  .then(function(a) { console.log(a); })
  .catch(function(e) { console.error('there was an error'); });

Will allow the Promise to handle the error and pass it to the catch function, resulting in ‘there was an error’ in the console.