Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    });
like image 727
Stanley Avatar asked Apr 14 '17 07:04

Stanley


People also ask

How do you handle a Promise rejection?

If an error condition arises inside a promise, you “reject” the promise by calling the reject() function with an error. To handle a promise rejection, you pass a callback to the catch() function. This is a simple example, so catching the rejection is trivial.

What happens when you reject a Promise Javascript?

The Promise. reject() method returns a Promise object that is rejected with a given reason.

What happens if Promise is rejected?

If the Promise rejects, the second function in your first . then() will get called with the rejected value, and whatever value it returns will become a new resolved Promise which passes into the first function of your second then. Catch is never called here either.

How do you handle reject In await?

Handling rejected promises You can handle rejected promises without a try block by chaining a catch() handler before awaiting the promise.


3 Answers

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)
  });
like image 109
JLRishe Avatar answered Oct 26 '22 09:10

JLRishe


Since the error doesn't involve the async code, a regular try-catch should do fine here:

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

Note that when the async-await pattern finally becomes the native way of resolving promises, the try-catch will also become the native way of handling errors:

try {
    var ok = await testError();
    console.log(ok)
}
catch(e) {
    console.log('e:' +e);
}

As one can easily verify, this one correctly handles both the sync and the async error and is much cleaner than then-catch.

like image 34
Wiktor Zychla Avatar answered Oct 26 '22 10:10

Wiktor Zychla


If you can, rewrite your testError function like so

function testError () {
  return new Promise(function (resolve, reject) {
     throw new Error('new error')
     resolve(123)
  })
}

testError().then(ok => console.log(ok),
                 err => console.error(err.message))
  1. Run it once to see it throw the error in console.error
  2. Comment out the throw line to see the promise resolve successfully
like image 28
Mulan Avatar answered Oct 26 '22 08:10

Mulan