Uncaught Exceptions


Uncaught exceptions in node js

Uncaught Exceptions in node js 

        In node js, we handle normal exceptions like given below. handling exception is necessary to avoid the unexpected server stop. exception stop servers if not handled properly. which is a nightmare for any developer especially in the production extra care needs to take. 
        Uncaught exceptions are different than normal exceptions.it needs to handle in the main server file.
  try{
// your code 
}catch(e){
console.log(e)
} 


But still, there are some exceptions which do not come under these exceptions. which we need to handle.

E.g 

        If something wrong happens in the program and your program gets restarted by default in node js you have no control over server restart. To handle this situation you need to handle it manually in coding lets see how we can handle it.


async function safeExit(signal) {
    // do all the necessary operations that you were going to if the
// player disconnects or exits abruptly
    logger.error("Error " + signal, "safeExit", currentFileName);
    // mongoose.connection.close()
    // redisClient.end();
    // expressConnection.close();
    // io.close()
    process.exit(1);

}

process.on("exit", () => safeExit("EXIT"));
process.on("SIGINT", () => safeExit("SIGINT"));
process.on("SIGHUP", () => safeExit("SIGHUP"));
process.on("uncaughtException", (err) => {
    console.log('uncaughtException');
    // console.error(err, "Uncaught Exception thrown");
    safeExit("uncaughtException");
});

app.listen(port, () => {
});

Add the above lines of code in your main server file. 


Description :

        Here we are using the process in node js gives you all the necessary information on the running node process. e.g id, set groups, unmask, etc.

The process object has some lifecycle events attached such as beforeExit, the exit we can use that event to know why the process exit or we can also take necessary actions before it completely exits. we can log errors, we can try to handle that exception, we can close open connections properly, etc actions we can take before it gets an exit.


process.on('beforeExit', (code) => {
  console.log('Process beforeExit event with code: ', code);
});

process.on('exit', (code) => {
  console.log('Process exit event with code: ', code);
});

Post a Comment

0 Comments