Search code examples
javascriptnode.jses6-promise

UnhandledPromiseRejectionWarning after catching a rejected promise


Running the following code with Node v8.1.4:

testPromise((err) => {
  if (err) throw err;
});

function testPromise(callback) {
  Promise.reject(new Error('error!'))
  .catch((err) => {
    console.log('caught');
    callback(err);
  });
}

returns the following:

caught
(node:72361) UnhandledPromiseRejectionWarning: Unhandled promise rejection 
(rejection id: 2): Error: test
(node:72361) [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.

I would have expected an uncaughtException to be thrown? How can I turn this into an uncaught exception?


Solution

  • You are essentially throwing inside the catch callback. This is caught and turned into another rejected promise. So you'll get no uncaughtException

    Promise.reject("err")
    .catch(err => {
        throw("whoops") //<-- this is caught
    })
    .catch(err => console.log(err)) // and delivered here -- prints "whoops"
    

    One thing to be careful of is asynchronous function that throw. For example this IS an uncaught exception:

    Promise.reject("err")
       .catch(err => {
          setTimeout(() => {
              throw("whoops")   // <-- really throws this tim
       }, 500)
    })
    .catch(err => console.log(err)) //<-- never gets caught.