title: How to handle a redis connection error in express?
body: <p>I have an express database that connects to multiple redis servers by receiving the connection ip from a client.</p>
  <p>It works fine if the redis database exists. The problem im facing is that if the ip doesnt exist, I will receive a</p>
  <blockquote>
  <p>Error: Error: Redis connection to xxxx failed - connect ECONNREFUSED
  xxx</p>
  </blockquote>
  <p>Being this totally understandable, but the problem is that my connection object is still defined. And i cant really seem how to identify this object as a failed connection.
  The only hint i might have might be in the <code>connection._events.error</code> variable, but it returns a <code>[Function]</code></p>
  <p>This is my code</p>
  <pre><code>let connections = []
  
  const killRedis = (redisClient, ip, port) =&gt; {
      redisClient.quit()
      connections = connections.filter((i) =&gt; { return i.ip !== ip &amp;&amp; i.port != port })
  }
  
  const subscribe = (redisClient, url, port) =&gt; {
      redisClient.on('error', function (err) {
          //this is supposed to handle the error, but i dont know how to make the &quot;undefined&quot; value available for the createRedisClient function. Since this seems to be delayed
          killRedis(redisClient, url, port)
          return undefined;
      });
      redisClient.on('connect', function () {
          console.log('Connected to Redis');
          return redisClient;
      });
  }
  
  findConnection = (ip, port) =&gt; {
      let connection = connections.filter(i =&gt; i.ip == ip &amp;&amp; i.port == port)
  
      if (connection &amp;&amp; connection.length &gt; 0) {
  
          return connection[0].connection
      } else {
          connections.push({
              ip: ip,
              port: port,
              connection: require('redis').createClient(port, ip, {
                  no_ready_check: true,
                  db: 1
              })
          })
          let pushedConnection = connections.filter(i =&gt; i.ip == ip &amp;&amp; i.port == port)[0].connection
          subscribe(pushedConnection, ip, port)
          return pushedConnection
      }
  }
  const createRedisClient = async (port, url) =&gt; {
      let redisClient = findConnection(url, port)
      console.log(redisClient._events.error) //[Function]
      return redisClient // this is always a connection object, even if the connection is faulty
  }
  module.exports = { createRedisClient }
  </code></pre>