diff --git a/connection.ts b/connection.ts index 1754da81..68b6b08d 100644 --- a/connection.ts +++ b/connection.ts @@ -360,15 +360,18 @@ export class RedisConnection return command.reject(error); } + let backoff = 0; for (let i = 0; i < this.maxRetryCount; i++) { // Try to reconnect to the server and retry the command this.#close(true); try { + this.#dispatchEvent("reconnecting", { delay: backoff }); await this.connect(); const reply = await command.execute(); return command.resolve(reply); - } catch { // TODO: use `AggregateError`? - const backoff = this.backoff(i); + } catch (error) { + this.#dispatchEvent("error", { error }); // TODO: use `AggregateError`? + backoff = this.backoff(i); await delay(backoff); } } diff --git a/tests/reconnect_test.ts b/tests/reconnect_test.ts index 8f6b907c..80f0eab6 100644 --- a/tests/reconnect_test.ts +++ b/tests/reconnect_test.ts @@ -1,4 +1,4 @@ -import { assertEquals } from "../deps/std/assert.ts"; +import { assertEquals, assertInstanceOf } from "../deps/std/assert.ts"; import { beforeAll, describe, it } from "../deps/std/testing.ts"; import { newClient, nextPort, startRedis, stopRedis } from "./test_util.ts"; @@ -13,10 +13,16 @@ describe("reconnect", () => { const client = await newClient({ hostname: "127.0.0.1", port }); assertEquals(await client.ping(), "PONG"); await stopRedis(server); + let reconnectingFired = 0; + client.addEventListener("reconnecting", (e) => { + reconnectingFired++; + assertInstanceOf(e, CustomEvent); + }); server = await startRedis({ port }); assertEquals(await client.ping(), "PONG"); client.close(); await stopRedis(server); + assertEquals(reconnectingFired, 1); }); it("auto reconnect, with db spec", async () => {