I've been searching for a while to find a way to trigger an error / catch from within a promise 'then' method.
Consider the following:
myPromiseToFetchAColor().then( (color) => {
if(color == "red"){
//THROW THE CATCH....with an error message
} else {
return aNewPromise();
}
}).catch( (error => {
console.log(error)
})
I know I can use another promise (a custom promise to do the validation on the color and then return the promise etc... but this seems over-kill. I'd love to just do my validation and then decide to continue, or through and error and trigger the catch.
CodePudding user response:
Below is a reproducible example based on the code you've shown, so you can see the console output to help debug and understand the control flow. Because the code uses pseudorandom number generation to create different outcomes, you can repeatedly run it (press the "Run code snippet" button) to see differing results.
Promise.prototype.catch()
will catch all exceptions which occur in the original promise or prior .then()
callback functions in the chain.
/** @returns an element at a random index from the input array */
function getRandomElement (array) {
return array[Math.floor(Math.random() * array.length)];
}
/** @returns a promise that will resolve to "blue" or "red" */
function myPromiseToFetchAColor () {
return Promise.resolve(getRandomElement(['blue', 'red']));
}
/** @returns a promise that will resolve to "hello" */
function aNewPromise () {
return Promise.resolve('hello');
}
myPromiseToFetchAColor()
.then(color => {
console.log('The color was:', color);
if (color === 'red') {
throw new Error(`Uh oh... I didn't expect RED!`);
} else {
return aNewPromise();
}
})
.then(result => console.log(result)) // Logs "hello" if the color was "blue"
.catch(error => console.error(error)); // Logs the error if the color was "red"
CodePudding user response:
You can use: throw new Error('Color is red!'); in your if statement
For more details, you can read more at: https://www.w3schools.com/js/js_errors.asp in "throw" session