0

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.

Nathan Leggatt
  • 398
  • 1
  • 6
  • 18
  • 1
    What's the issue, exactly? Yes, `throw`ing something inside that if block will proceed directly to the `.catch` – CertainPerformance Dec 23 '22 at 02:25
  • You can throw an error from inside `then`. If you're getting an error I would imagine `myPromiseToFetchAColor()` doesn't return a promise or you have some other syntax error. – Brandon Dec 23 '22 at 02:33

2 Answers2

1

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"
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
  • This looks great. I was reading some articles online and I thought they were saying that throwing the error as you did, would not work. I think maybe I was chasing my tail and got lost in the trees of trying to find a solution. – Nathan Leggatt Dec 23 '22 at 04:58
-2

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

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • w3schools is (sadly still at this date) one of the worst possible websites you could throw at someone to use as a legitimate source of information, best coding practices. Also the answer alone has almost nothing to do with the specific question. – Roko C. Buljan Aug 24 '23 at 20:39