Search code examples
node.jsuncaught-exception

In node.js how to restart the server while handling some exception in uncaughtException


In my application im using uncaughtException to handle the application error.In this how can i restart the server.


Solution

  • Use the forever module.

    npm install forever
    

    forever will restart your server any time it quits, for any reason.

    This means you can do a process.exit(); in your code any time you want the server to restart.

    You'll need a start and stop script to engage forever.

    A typical start script would look like this.

    #!/bin/sh
    ./node_modules/forever/bin/forever \
     start \
     -al log.forever \
     -ao log.traffic \
     -ae log.errors \
    app.js
    

    A typical stop script would look like this:

    #!/bin/sh
    ./node_modules/forever/bin/forever stop app.js
    

    In your exception handling code would look something like this:

    process.on('uncaughtException', function (err) {
        console.log(err.stack);
        process.exit();
    });