Skip to content

Commit

Permalink
Handle client errors in pool.query (#131)
Browse files Browse the repository at this point in the history
If an error not related to the query occurs, the client is emitting an
error event.

Forward this event to the callback.
  • Loading branch information
johanneswuerbach authored and brianc committed Dec 18, 2019
1 parent c8c41c5 commit 236db38
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
18 changes: 18 additions & 0 deletions index.js
Expand Up @@ -316,13 +316,31 @@ class Pool extends EventEmitter {
}
const response = promisify(this.Promise, cb)
cb = response.callback

this.connect((err, client) => {
if (err) {
return cb(err)
}

let clientReleased = false
const onError = (err) => {
if (clientReleased) {
return
}
clientReleased = true
client.release(err)
cb(err)
}

client.once('error', onError)
this.log('dispatching query')
client.query(text, values, (err, res) => {
this.log('query dispatched')
client.removeListener('error', onError)
if (clientReleased) {
return
}
clientReleased = true
client.release(err)
if (err) {
return cb(err)
Expand Down
15 changes: 15 additions & 0 deletions test/error-handling.js
Expand Up @@ -226,4 +226,19 @@ describe('pool error handling', function () {
})
})
})

it('handles post-checkout client failures in pool.query', (done) => {
const pool = new Pool({ max: 1 })
pool.on('error', () => {
// We double close the connection in this test, prevent exception caused by that
})
pool.query('SELECT pg_sleep(5)', [], (err) => {
expect(err).to.be.an(Error)
done()
})

setTimeout(() => {
pool._clients[0].end()
}, 1000)
})
})

0 comments on commit 236db38

Please sign in to comment.