Skip to content

Commit 37e1fc1

Browse files
authored
Improve error handling (#100)
* Improve connection errors handling after startup * Remove error event listener after initial connection * Do not return the client if `lazyConnect` is falsy * Refactor and allow for reconnection attempts * Call `onEnd` directly without emitting `end` event
1 parent 1fa3582 commit 37e1fc1

File tree

2 files changed

+48
-8
lines changed

2 files changed

+48
-8
lines changed

index.js

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,12 +65,44 @@ function fastifyRedis (fastify, options, next) {
6565
}
6666

6767
if (!redisOptions.lazyConnect) {
68-
return client.info((err, _) => {
69-
return err ? next(err) : next()
70-
})
71-
} else {
72-
next()
68+
const onEnd = function (err) {
69+
client
70+
.off('ready', onReady)
71+
.off('error', onError)
72+
.off('end', onEnd)
73+
.quit(() => next(err))
74+
}
75+
76+
const onReady = function () {
77+
client
78+
.off('end', onEnd)
79+
.off('error', onError)
80+
.off('ready', onReady)
81+
82+
next()
83+
}
84+
85+
const onError = function (err) {
86+
// Swallow network errors to allow ioredis
87+
// to preform reconnection and emit 'end'
88+
// event if reconnection eventually
89+
// fails.
90+
// Any other errors during startup will
91+
// trigger the 'end' event.
92+
if (err instanceof Redis.ReplyError) {
93+
onEnd(err)
94+
}
95+
}
96+
97+
client
98+
.on('end', onEnd)
99+
.on('error', onError)
100+
.on('ready', onReady)
101+
102+
return
73103
}
104+
105+
next()
74106
}
75107

76108
function close (fastify, done) {

test/test.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,15 @@ test('fastify.redis should support url', (t) => {
7474
})
7575
this.quit = () => {}
7676
this.info = cb => cb(null, 'info')
77+
this.on = function (name, handler) {
78+
if (name === 'ready') {
79+
handler(null, 'ready')
80+
}
81+
82+
return this
83+
}
84+
this.off = function () { return this }
85+
7786
return this
7887
}
7988
})
@@ -377,7 +386,7 @@ test('Should not throw within different contexts', (t) => {
377386
})
378387

379388
test('Should throw when trying to connect on an invalid host', (t) => {
380-
t.plan(2)
389+
t.plan(1)
381390

382391
const fastify = Fastify({ pluginTimeout: 20000 })
383392
t.teardown(() => fastify.close())
@@ -388,8 +397,7 @@ test('Should throw when trying to connect on an invalid host', (t) => {
388397
})
389398

390399
fastify.ready((err) => {
391-
t.type(err, 'MaxRetriesPerRequestError')
392-
t.equal(err.message, 'Reached the max retries per request limit (which is 20). Refer to "maxRetriesPerRequest" option for details.')
400+
t.ok(err)
393401
})
394402
})
395403

0 commit comments

Comments
 (0)