I am going to outline (as briefly as possible) how to ensure a Node Application is restarted effectively if an uncaught exception is thrown, whether that exception is synchronous or asynchronous.
You will need to have the following NPM Packages installed. NPM PackagesList
Once NodeJs is installed, you will need to install the Express webserver Below is a screenshot of my app.js file which I created following the Express setup tutorial:
You will need to add global error handling logic for any synchronous request. This is done by the app.use method which acts as a handler. This method will need to be placed at the bottom of all requests.
Because of the Node's design it is not possible to catch an unhandled exception on an asynchronous callback. It is only possible if the API is coded in a way which allows for it, which may not always be the case when using a custom in house package.
You will need to register for the 'uncaughtexception' event and process unhandled exceptions.
The above logic now captures all errors sync or async, however the application will still terminate due to the
process.exit(1);
line. Now we need to use Forever. Forever is an npm package which will restart our node application once it crashes. Install the forever package npm install forever -g
and use the follow basic configuration file.Save this file at the root of your application and call it forever.json
At the terminal run
forever start ./forever.json
This will start the background process for your node application, and it will ensure that your application restarts in the event of an unhandled exception.