Question

The code in question: app.js

var redis = require('redis');
var redisClient = redis.createClient();
redisClient.on('error', function (err) {
  console.error('There was an Error ' + err);
});

// do stuff

redisClient.quit(function(err, res) {
  console.log('closing redis client.');
});

I'm trying to use node_redis to connect to Redis from my node.js app. However, I'm not too sure how to handle the case where Redis is down.

I've got a bunch of client.on('error', function(err) {})'s but they never seem to be called. Is that the proper way to handle it? Am I calling it wrong?

I've just started using redis/node/express, so please excuse my ignorance.

EDIT As Vadim helped me realize, it seems that I am actually properly catching the error with client.on('error') in app.js. However, it's my routes that cannot catch the errors when redis is down.

Était-ce utile?

La solution

Since node_redis is asynchronous, the redisClient.on('error') callback isn't being called in time before I started to send other commands to redisClient.

The way I fixed this issue was by putting "success" code in the redisClient.on('connect') handler, which would only be called after redisClient has successfully connected. And my fallback code in redisClient.on('error').

You can see more about how I fixed this problem in this github changeset.

Autres conseils

I think the end event is what you need.

client will emit end when an established Redis server connection has closed.

Update:

If you are using node.js >= 0.8.0 you can use the domain module functionality for catching errors in asynchronous code.

You can use the connect-domain module for your express/connect application. It allow you to throw an error in asynchronous code and catch it with your error handler.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top