4

No browser, o código a seguir funciona normalmente:

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

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

Mas no Node.js (versão 8.10.0), ao executar o mesmo código, eu recebo o erro:

(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.

O que é isso? Por que acontece? Isso é prejudicial? Como resolver?

0

2 Respostas 2

10

O evento unhandledRejection é emitido sempre que um Promise é rejeitado e nenhum manipulador de erro é anexado à promessa.

Para resolver, basta apenas tratar a rejeição:

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

O código completo:

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

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

Veja funcionando no console do navegador em stackblitz e em um terminal em repl.it

-3

No meu caso foi a versão errada do node no terminal. Tinha fechado o projeto para recarregar uma extensão e esqueci do nvm use. Simples.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .