diff --git a/lib/postgresql.js b/lib/postgresql.js index 7771f8c7..e2f72981 100644 --- a/lib/postgresql.js +++ b/lib/postgresql.js @@ -80,16 +80,7 @@ function PostgreSQL(postgresql, settings) { } this.clientConfig.Promise = Promise; this.pg = new postgresql.Pool(this.clientConfig); - - if (settings.onError) { - if (settings.onError === 'ignore') { - this.pg.on('error', function(err) { - debug(err); - }); - } else { - this.pg.on('error', settings.onError); - } - } + attachErrorHandler(settings, this.pg); this.settings = settings; debug('Settings %j', { @@ -109,6 +100,18 @@ function PostgreSQL(postgresql, settings) { }); } +function attachErrorHandler(settings, pg) { + if (settings.onError) { + if (settings.onError === 'ignore') { + pg.on('error', function(err) { + debug(err); + }); + } else { + pg.on('error', settings.onError); + } + } +} + // Inherit from loopback-datasource-juggler BaseSQL util.inherits(PostgreSQL, SqlConnector); @@ -125,6 +128,10 @@ PostgreSQL.prototype.multiInsertSupported = true; PostgreSQL.prototype.connect = function(callback) { const self = this; self.pg.connect(function(err, client, releaseCb) { + // pg-pool requires attaching an error handler to each item checked out off the pool, + // which will handle connection-level errors. + // See https://github.com/brianc/node-postgres/issues/1324 + attachErrorHandler(self.settings, client); self.client = client; process.nextTick(releaseCb); callback && callback(err, client); @@ -194,6 +201,10 @@ PostgreSQL.prototype.executeSQL = function(sql, params, options, callback) { } else { self.pg.connect(function(err, connection, releaseCb) { if (err) return callback(err); + // pg-pool requires attaching an error handler to each item checked out off the pool, + // which will handle connection-level errors. + // See https://github.com/brianc/node-postgres/issues/1324 + attachErrorHandler(self.settings, connection); executeWithConnection(connection, releaseCb); }); }