Error. UnhandledPromiseRejectionWarning

0

In the browser, the following code works normally (how it should work):

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

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

But in NodeJs (version 8.10.0 ), while 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 this? Why does it happen? Is that harmful? How to solve?

    
asked by anonymous 22.03.2018 / 01:40

1 answer

1

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

To solve, just deal with 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 working in the browser console in stackblitz and in a terminal at repl.it

    
22.03.2018 / 03:24