Node.js Server Crash Handling

1.7k Views Asked by At

Is there any way i can do some database updation things whenever my node.js server crashes or stopped. Like try{}catch(){}finally(){} in JAVA. I am a bit newbie here.

Is there any events will node emit before it going shutdown. If so i can write my function there.

I have scenario,if i stop the server manually,i need to update some fields in the database. The same is for Unhandled crashes also.

i here about domain in Node.js. But i have no idea how to monitor a whole server using domain.

2

There are 2 best solutions below

1
Emmett On BEST ANSWER

An event is emitted when the node process is about to exit:

process.on('exit', function(code) {
    console.log('About to exit with code:', code);
});

http://nodejs.org/api/process.html#process_event_exit

You can't query the database here though, since this handler can only perform synchronous operations. Some possible alternatives:

  • use database transactions so you never need to do "database updation things" when your app crashes
  • use a tool like Upstart to automatically restart your process, and then do database fixup stuff whenever your process starts
0
Simcha On

When you are using node JS it's bad practice to use try / catch, because of big number of asynchronous calls. The best practice here to use "promises" review next link, there you can find a good explanation: https://www.promisejs.org/