admin管理员组

文章数量:1279180

I have a simple program, which needs to make sure I can connect to a Redis server. I use node-redis to connect and need to wait until Redis is started. I use this piece of code:

function initializeRedis(callback) {
    (function createClient(){
        var runner;
        try {
            client = redis.createClient();
        } catch (e) {
            setTimeout(createClient, 1000);
        }
        callback();
    })();
};

initializeRedis(function() {
// Work here
});

This is because without the try/catch, I got an exception from node.js:

 node.js:134
         throw e; // process.nextTick error, or 'error' event on first tick
         ^ Error: Redis connection to 127.0.0.1:6379 failed - ECONNREFUSED, Connection refused
     at Socket.<anonymous> (/var/www/php-jobs/node_modules/redis/index.js:88:28)
     at Socket.emit (events.js:64:17)
     at Array.<anonymous> (net.js:830:27)
     at EventEmitter._tickCallback (node.js:126:26)

When I start redis-server (Ubuntu machine) and start this script, everything works fine. If I stop redis-server and start the script, it doesn't catch the exception and still throws this same exception. How is that possible? I have a try/catch statement!

I have a simple program, which needs to make sure I can connect to a Redis server. I use node-redis to connect and need to wait until Redis is started. I use this piece of code:

function initializeRedis(callback) {
    (function createClient(){
        var runner;
        try {
            client = redis.createClient();
        } catch (e) {
            setTimeout(createClient, 1000);
        }
        callback();
    })();
};

initializeRedis(function() {
// Work here
});

This is because without the try/catch, I got an exception from node.js:

 node.js:134
         throw e; // process.nextTick error, or 'error' event on first tick
         ^ Error: Redis connection to 127.0.0.1:6379 failed - ECONNREFUSED, Connection refused
     at Socket.<anonymous> (/var/www/php-jobs/node_modules/redis/index.js:88:28)
     at Socket.emit (events.js:64:17)
     at Array.<anonymous> (net.js:830:27)
     at EventEmitter._tickCallback (node.js:126:26)

When I start redis-server (Ubuntu machine) and start this script, everything works fine. If I stop redis-server and start the script, it doesn't catch the exception and still throws this same exception. How is that possible? I have a try/catch statement!

Share Improve this question asked Nov 9, 2011 at 20:35 Jurian SluimanJurian Sluiman 13.6k3 gold badges69 silver badges101 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

After client = redis.createClient();, set a handler for the error event:

client.on('error', function(err) {
  // handle async errors here
});

Have a look at the stack trace - your code isn't in it, so there's no place where a try/catch could catch the error.

本文标签: javascriptCatch exception in nodejsStack Overflow