Search code examples
javascriptpromisees6-promiserequest-promise

Handling Js promise rejection


How do you handle an error (eg. "new error" below) that is outside of the promise?

function testError() {
    throw new Error("new error") // how to handle this?
    var p123 = new Promise(function(resolve, reject) {
         resolve(123)
    });
    return p123
};

testError().catch(err => {
        return err;  // code doesn't come here
    })
    .then(ok => {
        console.log(ok)
    });

Solution

  • If you're not sure whether a function will throw (or return a value) synchronously, you can call it using .then(). This will wrap it so that the result will be handled consistently no matter how it is produced:

    function testError() {
      throw new Error("new error") // how to handle this?
      var p123 = new Promise(function(resolve, reject) {
        resolve(123)
      });
      return p123
    };
    
    Promise.resolve()
      .then(testError)
      .catch(err => {
        console.error(err);
        return err; 
      })
      .then(ok => {
        console.log(ok.message)
      });