简体   繁体   中英

Catch exception in node.js

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM