Skip to content

Commit 86ebae8

Browse files
Quentin-Mdhmlau
authored andcommitted
fix: add missing connection error handler in pool, resolving process crash
pg-pool requires attaching an error handler to each item checked out off the pool, which will handle connection-level errors. Without it, the application straight-up crashes whenever the connection is interrupted (e.g. database failover). See brianc/node-postgres#1324 Signed-off-by: Quentin Machu <quentin@bitmex.com>
1 parent cf21bd3 commit 86ebae8

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

lib/postgresql.js

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -80,16 +80,7 @@ function PostgreSQL(postgresql, settings) {
8080
}
8181
this.clientConfig.Promise = Promise;
8282
this.pg = new postgresql.Pool(this.clientConfig);
83-
84-
if (settings.onError) {
85-
if (settings.onError === 'ignore') {
86-
this.pg.on('error', function(err) {
87-
debug(err);
88-
});
89-
} else {
90-
this.pg.on('error', settings.onError);
91-
}
92-
}
83+
attachErrorHandler(settings, this.pg);
9384

9485
this.settings = settings;
9586
debug('Settings %j', {
@@ -109,6 +100,18 @@ function PostgreSQL(postgresql, settings) {
109100
});
110101
}
111102

103+
function attachErrorHandler(settings, pg) {
104+
if (settings.onError) {
105+
if (settings.onError === 'ignore') {
106+
pg.on('error', function(err) {
107+
debug(err);
108+
});
109+
} else {
110+
pg.on('error', settings.onError);
111+
}
112+
}
113+
}
114+
112115
// Inherit from loopback-datasource-juggler BaseSQL
113116
util.inherits(PostgreSQL, SqlConnector);
114117

@@ -125,6 +128,10 @@ PostgreSQL.prototype.multiInsertSupported = true;
125128
PostgreSQL.prototype.connect = function(callback) {
126129
const self = this;
127130
self.pg.connect(function(err, client, releaseCb) {
131+
// pg-pool requires attaching an error handler to each item checked out off the pool,
132+
// which will handle connection-level errors.
133+
// See https://github.com/brianc/node-postgres/issues/1324
134+
attachErrorHandler(self.settings, client);
128135
self.client = client;
129136
process.nextTick(releaseCb);
130137
callback && callback(err, client);
@@ -194,6 +201,10 @@ PostgreSQL.prototype.executeSQL = function(sql, params, options, callback) {
194201
} else {
195202
self.pg.connect(function(err, connection, releaseCb) {
196203
if (err) return callback(err);
204+
// pg-pool requires attaching an error handler to each item checked out off the pool,
205+
// which will handle connection-level errors.
206+
// See https://github.com/brianc/node-postgres/issues/1324
207+
attachErrorHandler(self.settings, connection);
197208
executeWithConnection(connection, releaseCb);
198209
});
199210
}

0 commit comments

Comments
 (0)