skip to Main Content

I’m using the redis npm package in a TypeScript Node.js app. If redis fails to connect, it takes my app down with it regardless of how many try-catch blocks I use. Modifying the client.on("error"... hook doesn’t have an effect.

The following code (from 2016) is supposed to solve the issue:

const client = redis.createClient({
  retry_strategy: function (options) {
    if (options.error.code === "ECONNREFUSED") {
      // This will suppress the ECONNREFUSED unhandled exception
      // that results in app crash
      return;
    }
  }
});

However I get a TypeScript error:

Argument of type '{ retry_strategy: (options: any) => void; }' is not assignable to parameter of type 'RedisClientOptions<RedisModules, RedisFunctions, RedisScripts>'.

Even if I add @ts-ignore, the solution above has no effect.

Another way to solve this is to use ioredis, but I want to use the redis package. Any ideas how to solve this?

2

Answers


  1. Chosen as BEST ANSWER

    So far the only working solution (that doesn't rely on other libraries) seems to be to disconnect when encountering an error:

    client.on("error", (e) => {
      // handle error
      client.disconnect();
    });
    

  2. In case of an error (such as a network error), the client will emit an error event (which you’ll have to handle, otherwise the process will crash. see here) -> call reconnectStrategy (which in most cases you shouldn’t override, the default one will retry with a backoff between 0-500ms, depends of the number of retries) to decide if it needs to reconnect, and the backoff strategy -> reconnect to the server -> keep processing the commands in the queue.
    You can read more about this here and here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search