Search code examples
node.jspromiseasync-awaitwarningsunhandled-exception

How to find which promises are unhandled in Node.js UnhandledPromiseRejectionWarning?


Node.js from version 7 has async/await syntactic sugar for handling promises and now in my code the following warning comes up quite often:

(node:11057) UnhandledPromiseRejectionWarning: Unhandled promise 
rejection (rejection id: 1): ReferenceError: Error: Can't set headers 
after they are sent.
(node:11057) 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.

Unfortunately there's no reference to the line where the catch is missing. Is there any way to find it without checking every try/catch block?


Solution

  • listen unhandledRejection event of process.

    process.on('unhandledRejection', (reason, p) => {
      console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
      // application specific logging, throwing an error, or other logic here
    });