Exception exception in node.js

I have a simple program that needs to be sure that I can connect to a Redis server. I use node-redis to connect and have 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 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 the redis server (Ubuntu machine) and run this script, everything works fine. If I stop the redis server and run the script, it will not catch the exception and still throw the same exception. How is this possible? I have a try / catch statement!

+3
source share
1 answer

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

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

Look at the stack trace - your code is not in it, so there is no place where try / catch can catch the error.

+8
source

Source: https://habr.com/ru/post/908648/


All Articles