4

I'm using node-redis module to connect to redis.
So, I'm attaching an event listener to handle the case where redis server connection cannot be established.

client = redis.createClient(6379, 'localhost')
client.on('error',(err)=>{
    console.log('redis connection refused')
})

This is the error that occurs without the listener.

events.js:141
  throw er; // Unhandled 'error' event
  ^
Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14)

Now my question is, when does this event listener get attached to 'client'. Is it possible that the connection refused error be thrown before the event listener is attached?

Jeff P Chacko
  • 4,908
  • 4
  • 24
  • 32

1 Answers1

2

It is possible, but not when you run the commands next to each other as you do. This code will give the same error that you pasted:

client = redis.createClient(6379, 'localhost')
setTimeout(function() {
    client.on('error',(err)=>{
        console.log('redis connection refused')
    })
}, 3000);

The reason that this will not happen in your code, is that the node thread will not yield to event handling when running in your thread, so event handling will happen after your error handler has been attached.

You can listen for uncaught error events globally, to catch errors that happen before you can attach.

process.on('uncaughtException', (err) => {
  console.log('whoops! there was an error');
});
bolav
  • 6,938
  • 2
  • 18
  • 42
  • Client will not yield to event handling? Can you explain more? – Jeff P Chacko Feb 19 '16 at 04:47
  • Your thread that creates the client, and adds the handler will continue to run, and not allow the error event to be handled before it returns from the thread into the event loop. Look here: http://stackoverflow.com/questions/8982489/how-does-asynchronous-programming-work-in-a-single-threaded-programming-model , [quora answer](https://www.quora.com/How-does-a-single-thread-handle-asynchronous-code-in-JavaScript) . Doing `setTimeout(func, 0)` for the rest of your code is one way to force return to the even loop. – bolav Feb 19 '16 at 09:22