Skip to content

Commit

Permalink
feat: do not emit "error" events anymore
Browse files Browse the repository at this point in the history
Previously, the "error" events from the two Redis clients were
forwarded by each instance of the adapter, which made it quite hard to
handle the errors with a lot of namespaces (as there is one instance of
adapter per namespace).

```js
io.of("/my-namespace").adapter.on("error", () => {
  // ...
});
```

The adapter instance will no longer emit "error" events, and will print
a warning if there is no other error handler registered (for backward
compatibility).

The error handling must be done directly on the Redis client:

```js
redisClient.on("error", (err) => {
  // something went wrong, maybe the connection to the server was lost
});
```

Related:

- #412
- #425
  • Loading branch information
darrachequesne committed Nov 29, 2021
1 parent f66de11 commit 8e5c84f
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,6 @@ export class RedisAdapter extends Adapter {
this.responseChannel = prefix + "-response#" + this.nsp.name + "#";
const specificResponseChannel = this.responseChannel + this.uid + "#";

const onError = (err) => {
if (err) {
this.emit("error", err);
}
};

const isRedisV4 = typeof this.pubClient.pSubscribe === "function";
if (isRedisV4) {
this.subClient.pSubscribe(
Expand All @@ -136,18 +130,27 @@ export class RedisAdapter extends Adapter {
}
);
} else {
this.subClient.psubscribe(this.channel + "*", onError);
this.subClient.psubscribe(this.channel + "*");
this.subClient.on("pmessageBuffer", this.onmessage.bind(this));

this.subClient.subscribe(
[this.requestChannel, this.responseChannel, specificResponseChannel],
onError
);
this.subClient.subscribe([
this.requestChannel,
this.responseChannel,
specificResponseChannel,
]);
this.subClient.on("messageBuffer", this.onrequest.bind(this));
}

this.pubClient.on("error", onError);
this.subClient.on("error", onError);
const registerFriendlyErrorHandler = (redisClient) => {
redisClient.on("error", () => {
if (redisClient.listenerCount("error") === 1) {
console.warn("missing 'error' handler on this Redis client");
}
});
};

registerFriendlyErrorHandler(this.pubClient);
registerFriendlyErrorHandler(this.subClient);
}

/**
Expand Down Expand Up @@ -211,7 +214,7 @@ export class RedisAdapter extends Adapter {
try {
request = JSON.parse(msg);
} catch (err) {
this.emit("error", err);
debug("ignoring malformed request");
return;
}

Expand Down Expand Up @@ -406,7 +409,7 @@ export class RedisAdapter extends Adapter {
try {
response = JSON.parse(msg);
} catch (err) {
this.emit("error", err);
debug("ignoring malformed response");
return;
}

Expand Down

0 comments on commit 8e5c84f

Please sign in to comment.