Stanley
Stanley

Reputation: 2816

Unable to handle errors in javascript promise

Why doesn't it run the code "console.log(err)" below? but instead returns "TypeError: Cannot create property 'uncaught' on string 'error in promise'"

function abc() {
    throw "error in promise";
    return 123;
};
abc().catch(function(err) {
    console.log(err)
}).then ( abcMessage =>
    console.log(abcMessage)
)

Upvotes: 1

Views: 92

Answers (1)

KevBot
KevBot

Reputation: 18908

.then and .catch require a Promise to be constructed. You are not returning a promise. The promise callback (executor) takes two arguments, a resolver, and a rejecter. Depending on what happens in the code, you may need to call resolve if everything goes right, or reject if something goes wrong.

function abc() {
  return new Promise(function(resolve, reject) {
    reject(123)
  });
};


abc()
  .catch(err => {
    console.log(err);
    return err;
  })
  .then(abcMessage => {
    console.log(abcMessage)
  });
new Error("error in promise")

Upvotes: 2

Related Questions