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?

4
  • Fix your errors? Wrap code with potential run-time errors in try ... catch blocks? How is this different from any other language/interpreter? Commented Oct 13, 2011 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. Commented Oct 13, 2011 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 developer.mozilla.org/en/JavaScript/Reference/Statements/… Commented Oct 13, 2011 at 23:41
  • 1
    See stackoverflow.com/questions/7310521/… Commented Oct 14, 2011 at 10:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Really really handy...it was starting to get annoying checking my log files
Is this still recommended? are there side effects to this?
This method of error handling is strongly discouraged on the Joylet website. joyent.com/developers/node/design/errors
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.