DEV Community

Cover image for Prevent app crash Node JS
Jorge Arraga
Jorge Arraga

Posted on

Prevent app crash Node JS

There are two main reasons why our node application crashes, uncaught exceptions, and unhandled rejections

While the correct way to fix this problem would be to handle all these exceptions and rejections, sometimes our application crashes due to a error in one part of the code, and this causes the entire app flow to not be able to continue

I show you how to prevent this behavior

The trick is add two listeners in the top of app, for the unhandled exceptions and rejections, this way:

process.on('uncaughtException', (error, origin) => {
    console.log('----- Uncaught exception -----')
    console.log(error)
    console.log('----- Exception origin -----')
    console.log(origin)
})

process.on('unhandledRejection', (reason, promise) => {
    console.log('----- Unhandled Rejection at -----')
    console.log(promise)
    console.log('----- Reason -----')
    console.log(reason)
})
Enter fullscreen mode Exit fullscreen mode

To demonstrate that works, I add a setInterval function next to the listeners

setInterval(() => {
    console.log('app still running')
}, 1000)
Enter fullscreen mode Exit fullscreen mode

And to make app crash, I call a function that doesn't exists

nonExistingFunction()
Enter fullscreen mode Exit fullscreen mode

As we can see, the uncaughtException runs, and app continues its execution

----- Uncaught exception -----
ReferenceError: nonExistingFunction is not defined
    at Object.<anonymous> (C:\Users\Jorge\Desktop\test\t.js:19:1)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
    at internal/main/run_main_module.js:17:47
----- Exception origin -----
uncaughtException
app still running
app still running
app still running
Enter fullscreen mode Exit fullscreen mode

I let you official node JS documentation:

Uncaught exception

Warning: Using 'uncaughtException' correctly

Unhandled rejection

Top comments (0)