Gracefully shutting down the application
Throughout the book, we have learned how to handle errors using try
/catch
blocks, error-first callbacks, catch
for promises, and also events to handle errors but, sometimes, we need to handle errors globally.
Node.js provides a way to handle errors globally and gracefully shut down the application when an error occurs: using process.on()
. You can also use process.exit()
to exit the application with a specific exit code. This is useful in CI/CD pipelines, to indicate whether or not the application was shut down because of an error, and also in productive environments.
Events
There are many events that can be used to handle errors globally:
uncaughtException
: This event is emitted when an uncaught exception occursunhandledRejection
: This event is emitted when an unhandled rejection occursexit
: This event is emitted when the Node.js process is about to exitSIGINT
andSIGTERM
: These events are emitted when the Node...