Error. Unhandledpromiserejectionwarning

Asked

Viewed 39,540 times

3

In the browser, the following code works normally:

const get = async () => {
  return Promise.reject('Oops!')
}

get()
  .then(console.log)
  .catch((err) => { throw new Error(err) })

But on Node.js (version 8.10.0), when executing the same code, I get the error:

(node:2508) UnhandledPromiseRejectionWarning: Error: Oops!
    at get.then.catch.err (C:\Users\fraza\Desktop\NodeTests\extra.test.js:5:46)
    at <anonymous>
    at runMicrotasksCallback (internal/process/next_tick.js:121:5)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
    at Function.Module.runMain (module.js:695:11)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3
(node:2508) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
(node:2508) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

What is it? Why does it happen? Is it harmful? How to solve?

1 answer

7


The event unhandledRejection is issued whenever a Promise is rejected and no error handler is attached to the promise.

To solve, just treat the rejection:

return Promise.reject('Oops!').catch(err => {
  throw new Error(err);
});

The complete code:

const get = async () => {
  return Promise.reject('Oops!').catch(err => {
    throw new Error(err);
  });
};

get()
  .then(console.log)
  .catch(function(e) {
    console.log(e);
  });

See how it works in the browser console on stackblitz and at a terminal in repl it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.