Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make node.js not exit on error

Tags:

node.js

I am working on a websocket oriented node.js server using Socket.IO. I noticed a bug where certain browsers aren't following the correct connect procedure to the server, and the code isn't written to gracefully handle it, and in short, it calls a method to an object that was never set up, thus killing the server due to an error.

My concern isn't with the bug in particular, but the fact that when such errors occur, the entire server goes down. Is there anything I can do on a global level in node to make it so if an error occurs it will simply log a message, perhaps kill the event, but the server process will keep on running?

I don't want other users' connections to go down due to one clever user exploiting an uncaught error in a large included codebase.

like image 831
RobKohr Avatar asked Nov 18 '10 09:11

RobKohr


People also ask

Which process event is emitted right before a node process crashes and exits?

When Node. js exits, it also emits several types of events. One of these is beforeExit , and as its name implies, it is emitted right before a Node process exits. You can provide an event handler which can make asynchronous calls, and the event loop will continue to perform the work until it's all finished.

What is exit code in NodeJS?

Exit code 1 is used when unhandled fatal exceptions occur that was not handled whereas Exit code 0 is used to terminate when no more async operations are happening.


1 Answers

You can attach a listener to the uncaughtException event of the process object.

Code taken from the actual Node.js API reference (it's the second item under "process"):

process.on('uncaughtException', function (err) {   console.log('Caught exception: ', err); });  setTimeout(function () {   console.log('This will still run.'); }, 500);  // Intentionally cause an exception, but don't catch it. nonexistentFunc(); console.log('This will not run.'); 

All you've got to do now is to log it or do something with it, in case you know under what circumstances the bug occurs, you should file a bug over at Socket.IO's GitHub page:
https://github.com/LearnBoost/Socket.IO-node/issues

like image 196
Ivo Wetzel Avatar answered Oct 09 '22 02:10

Ivo Wetzel