Skip to content

Commit

Permalink
Improve error handling (#100)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
MSE99 authored Jul 14, 2021
1 parent 1fa3582 commit 37e1fc1
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 8 deletions.
42 changes: 37 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,44 @@ function fastifyRedis (fastify, options, next) {
}

if (!redisOptions.lazyConnect) {
return client.info((err, _) => {
return err ? next(err) : next()
})
} else {
next()
const onEnd = function (err) {
client
.off('ready', onReady)
.off('error', onError)
.off('end', onEnd)
.quit(() => next(err))
}

const onReady = function () {
client
.off('end', onEnd)
.off('error', onError)
.off('ready', onReady)

next()
}

const onError = function (err) {
// Swallow network errors to allow ioredis
// to preform reconnection and emit 'end'
// event if reconnection eventually
// fails.
// Any other errors during startup will
// trigger the 'end' event.
if (err instanceof Redis.ReplyError) {
onEnd(err)
}
}

client
.on('end', onEnd)
.on('error', onError)
.on('ready', onReady)

return
}

next()
}

function close (fastify, done) {
Expand Down
14 changes: 11 additions & 3 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,15 @@ test('fastify.redis should support url', (t) => {
})
this.quit = () => {}
this.info = cb => cb(null, 'info')
this.on = function (name, handler) {
if (name === 'ready') {
handler(null, 'ready')
}

return this
}
this.off = function () { return this }

return this
}
})
Expand Down Expand Up @@ -377,7 +386,7 @@ test('Should not throw within different contexts', (t) => {
})

test('Should throw when trying to connect on an invalid host', (t) => {
t.plan(2)
t.plan(1)

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

fastify.ready((err) => {
t.type(err, 'MaxRetriesPerRequestError')
t.equal(err.message, 'Reached the max retries per request limit (which is 20). Refer to "maxRetriesPerRequest" option for details.')
t.ok(err)
})
})

Expand Down

0 comments on commit 37e1fc1

Please sign in to comment.