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)
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With