Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle unhandled exceptions in libraries in node.js

Tags:

node.js

redis

I have a node.js application using Express and Redis. My question is how do I catch and handle a Redis connection error. I have an app.error function in express which handles most application errors but since this error is an error that gets thrown in the redis library it becomes an uncaught exception and the whole app goes down.

Can I just define an on_error method on my redis client and that will do the trick? If so maybe some sample code? Should I somehow handle it in a node.js next tick error? I'm not sure I understand the next statement exactly so not sure what's the best practice.

In the code below the catch block never gets hit even if there is a connection error

try
{ 
  feedClient = redis.createClient(feedPort, feedHost);
}
catch (error)
{
  console.log('cannnot start redis' + error);
}

Here's the uncaught error

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: Redis connection to localhost:6379 failed - ECONNREFUSED, Connection refused
    at RedisClient.on_error (/node_modules/redis/index.js:136:24)
    at Socket. (/node_modules/redis/index.js:70:14)
    at Socket.emit (events.js:64:17)
    at Array. (net.js:830:27)
    at EventEmitter._tickCallback (node.js:126:26)
like image 721
MonkeyBonkey Avatar asked Feb 16 '12 17:02

MonkeyBonkey


People also ask

Which event is used for unhandled exception in node JS?

The 'uncaughtException' is an event of class Process within the process module which is emitted when an uncaught JavaScript exception bubbles all the way back to the event loop.


1 Answers

Yes, you need to specify an error handler:

feedClient = redis.createClient(feedPort, feedHost);
feedClient.on("error", function(err) {
  console.error("Error connecting to redis", err);
});
like image 73
Linus Thiel Avatar answered Oct 09 '22 11:10

Linus Thiel