8

I have a node.js script and anytime an error happens node.js stops running with the error that happened.

What is the proper way of checking errors in node.js so it won't break the script and cause node.js to stop?

Book Of Zeus
  • 49,509
  • 18
  • 174
  • 171
John
  • 9,840
  • 26
  • 91
  • 137
  • Fix your errors? Wrap code with potential run-time errors in `try ... catch` blocks? How is this different from any other language/interpreter? – nrabinowitz Oct 13 '11 at 23:16
  • @nrabinowitz So with try catch if an error occurs it wont break the script? And please forgive my lack of knowledge, very new to nodejs so its kind outside my comfort level. Trying to learn it. – John Oct 13 '11 at 23:21
  • yes, `try ... catch` in Javascript works the same way as in other languages, allowing you to catch and deal with errors in run-time code (though it won't help with parse-time errors, e.g. syntax errors). See https://developer.mozilla.org/en/JavaScript/Reference/Statements/try...catch – nrabinowitz Oct 13 '11 at 23:41
  • 1
    See http://stackoverflow.com/questions/7310521/node-js-best-practice-exception-handling/7313005#7313005 – balupton Oct 14 '11 at 10:53

2 Answers2

22

You can catch otherwise uncaught errors by setting the following:

process.on('uncaughtException', function (exception) {
   // handle or ignore error
  });

Of course, if you run your script in something like forever or node-supervisor, when your script "stops" it will start back up, which might solve your problem.

rob
  • 9,933
  • 7
  • 42
  • 73
3

Catching uncaughtException is no longer recommended.

Using domains are preferred. Using either "uncaughtException" or Domain, restarting the process is highly recommended after handling the exception.

To auto-restart the process, NodeJS provides another library called Cluster which assists in managing the worker threads.

neowulf33
  • 635
  • 2
  • 7
  • 19