Eli Levit
Eli Levit

Reputation: 67

Why "catch" doesn't handle rejected promise?

I have a very simple function that gets a number and returns a Promise. I don't understand why if the promise was rejected I can't catch it when I call this function? Instead node throws "Exception has occurred".

function check(num) {
  return new Promise((resolve , reject) => {
    if (num > 2) resolve('good')
    else reject('bad') 
  })
}

check(1)
 .then(res => console.log(res))
 .catch(err => console.log(err))

screenshot

Upvotes: 1

Views: 842

Answers (1)

Damaged Organic
Damaged Organic

Reputation: 8467

This code should run without any issues. The problem is in the IDE/debugger.

If you're using something like Microsoft Visual Studio Code and running with breakpoints, you should be able to set what kinds of exceptions IDE should throw.

Usually you can find several options in the debugging panel stating when to signal for exceptions, like All, Uncaught, Promise rejects, etc. So try to check the debug panel in your editor.

enter image description here

Upvotes: 4

Related Questions