6

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)
1

1 Answer 1

10

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

yah i was only handling it for one redis connection, had 3, didn't handle other two, couldn't figure out why was crapping out. +1
The redis node-module is internally prototyping EventEmitter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.