Making unhandled promise rejections crash the Node.js process

Thai Pangsakulyanont
1 min readAug 3, 2017

--

I want my code to fail loudly when there is an unexpected error. It’s usually bad when uncaught errors go unnoticed as it usually leads to incorrect behavior down the line.

For example, consider this Node.js script:

async function main () {
await meow
}
main()

Although the program is incorrect, running this code in Node 8.2.1 will not crash the program. Instead a warning is printed:

(node:69836) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: meow is not defined
(node:69836) [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.

To fast-forward to the future and make the script terminate (according to the deprecation warning), you can handle the unhandledRejection event on the process.

process.on('unhandledRejection', up => { throw up })

Now when you run the script, Node.js should now crash!

/tmp/meow.js:1
process.on('unhandledRejection', up => { throw up })
^
ReferenceError: meow is not defined
at main (/tmp/meow.js:4:9)
at Object.<anonymous> (/tmp/meow.js:7:1)
...

--

--

Thai Pangsakulyanont

(@dtinth) A software engineer and frontend enthusiast. A Christian. A JavaScript musician. A Ruby and Vim lover.