Andrey Bushman
Andrey Bushman

Reputation: 12476

Why I get the "(node:7424) UnhandledPromiseRejectionWarning" message for handled error?

I handle the error in my Promise by catch, but in Node.js (v10.11.0) console output I see the message: (node:7424) UnhandledPromiseRejectionWarning: Error: Oops...

Why does it happen?

// See browser console, not stack snippet console, to see uncaught error

const p = new Promise((resolve,reject) => { throw new Error('Oops..');});

p.then(()=> console.log('Then'));
p.catch(err => console.log(err.message)); // the error handling

console.log('The end');

Also, I get the same result for such variant of p initializing:

const p = new Promise((resolve,reject) => { reject(new Error('Oops..'));});

This is my output:

The end
Oops..
(node:7492) UnhandledPromiseRejectionWarning: Error: Oops..

Upvotes: 0

Views: 88

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

Whenever you call .then (or .catch) on an existing Promise, you have a new Promise. The error results from the Promise chain created by

p.then(()=> console.log('Then'));

not being caught anywhere.

Either chain the .catch onto the .then:

const p = new Promise((resolve, reject) => {
  throw new Error('Oops..');
});

p
  .then(() => console.log('Then'))
  .catch(err => console.log(err.message));

console.log('The end');

Note that when constructing a Promise, it's a good idea to always call reject explicitly when there's an error, to ensure that the consumer of that Promise can catch problems. For example, in the following code, the p will not be rejected, and will remain unresolved forever, because the error was thrown asynchronously:

const p = new Promise((resolve, reject) => {
  setTimeout(() => {
    throw new Error('Oops..');
  });
})

p
  .then(() => console.log('Then'))
  .catch(err => console.log(err.message))

console.log('The end');

Better to call reject:

const p = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('Oops..');
  });
})

p
  .then(() => console.log('Then'))
  .catch(err => console.log(err))

console.log('The end');

Upvotes: 2

Related Questions