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)
});
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.
The Promise. reject() method returns a Promise object that is rejected with a given reason.
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.
Handling rejected promises You can handle rejected promises without a try block by chaining a catch() handler before awaiting the promise.
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)
});
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
.
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))
console.error
throw
line to see the promise resolve successfullyIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With