Search code examples
javascriptnode.jspromisebluebird

Catching Errors in JavaScript Promises with a First Level try ... catch


So, I want my first level catch to be the one that handles the error. Is there anyway to propagate my error up to that first catch?

Reference code, not working (yet):

Promise = require('./framework/libraries/bluebird.js');

function promise() {
    var promise = new Promise(function(resolve, reject) {
        throw('Oh no!');
    });

    promise.catch(function(error) {
        throw(error);
    });
}

try {   
    promise();
}
// I WANT THIS CATCH TO CATCH THE ERROR THROWN IN THE PROMISE
catch(error) {
    console.log('Caught!', error);
}

Solution

  • With the new async/await syntax you can achieve this. Please note that at the moment of writing this is not supported by all browsers, you probably need to transpile your code with babel (or something similar).

    // Because of the "async" keyword here, calling getSomeValue()
    // will return a promise.
    async function getSomeValue() {
      if (somethingIsNotOk) {
        throw new Error('uh oh');
      } else {
        return 'Yay!';
      }
    }
    
    async function() {
      try {
        // "await" will wait for the promise to resolve or reject
        // if it rejects, an error will be thrown, which you can
        // catch with a regular try/catch block
        const someValue = await getSomeValue();
        doSomethingWith(someValue);
      } catch (error) {
        console.error(error);
      }
    }