Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node Exception Handling

Node Exception Handling

Problem

What is the best way in node to handle unhandled expections that are coming out of core node code? I have a background process that runs and crawls web content and will run for long periods of time without issue, but every so often an unexpected exception occurs and I can't seem to gracefully handle it. The usual culprit appears to be some networking issue (lost connectivity) where the http calls I'm making fail. All of the functions that I have created follow the pattern of FUNCTION_NAME(error, returned_data), but in the situations where the error occurs I'm not seeing any of the functions I created in the call stack that is printed out, instead its showing some of the core node modules. I'm not really worried about these infrequent errors and their root cause, the purpose of this posting is just trying to find a graceful way of handling these Exceptions.

I've tried putting a try/catch at the top level of my code where everything runs under but it doesn't seem to capture these exceptions. Is it good practice in node to use try/catch within all the lower level functions that use any core code? Or is there some way to globally capture all unhandled exceptions?

Thanks

Chris

UPDATED TO ADD STACK

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: connect Unknown system errno 10060
    at errnoException (net.js:642:11)
    at Object.afterConnect [as oncomplete] (net.js:633:18)
Problem courtesy of: Chris Dellinger

Solution

is there some way to globally capture all unhandled exceptions?

You can catch all exceptions using process.on('uncaughtException'). Listening to this event will avoid the default action of printing the stack and exiting. However be conscious that ignoring exceptions may lead to problems in your app execution.

Link: http://nodejs.org/docs/latest/api/process.html#process_event_uncaughtexception

Pay attention to the documentation advice:

Note that uncaughtException is a very crude mechanism for Exception Handling. Using try / catch in your program will give you more control over your program's flow. Especially for server programs that are designed to stay running forever, uncaughtException can be a useful safety mechanism.

Solution courtesy of: seppo0010

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node Exception Handling

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×