pg client.on('error' 未检测到网络中断



我的应用程序连接到数据库并侦听事件,这样它就可以执行事件。如果与数据库的连接断开,那么它应该能够用consumer.db.on('error'检测到它

相关文件:

client.on('error',(err:error(=>void(=>无效

当客户端在连接、调度查询或断开连接的过程中,它会捕获并将错误从PostgreSQL服务器转发到相应的客户端;然而,客户端与PostgreSQL后端保持长期连接,由于网络分区、后端崩溃、故障转移等原因,客户端最终可能(并且在足够长的时间内(在空闲时断开连接。要处理此问题,您可能需要将错误侦听器附加到客户端以捕获错误。这里有一个人为的例子:

const client = new pg.Client()
client.connect()
client.on('error', (err) => {
console.error('something bad has happened!', err.stack)
})
// walk over to server, unplug network cable
// process output: 'something bad has happened!' followed by stacktrace :P

这是我的代码,试图做同样的事情:

var pg = require('pg');
// get the connection from the connection pool
pg.connect('pg://some:user@some.server', function(err, db){
// throw error
if(err) {
// handle the error - reconnect and log
}
// set database connection for global use
consumer.db = db;
// when notification received
consumer.db.on('notification', function(event){
console.log(event);
// do something with the event
});
// Detect network disruption and other errors
consumer.db.on('error', function(event){
console.log("Error!")
// handle the error - reconnect and log
});
});

我通过关闭wifi 5分钟来测试这个功能。果不其然,连接已断开,但没有创建任何错误事件,也没有向控制台记录任何内容。我还尝试关闭远程数据库,结果相同。

连接断开时如何出错?

问题是pg的旧版本

在v7.0.0中删除了默认池和pg.connect(...):https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md#700

此外,看起来client.on('error', ...)当时不支持网络中断。

升级到^7.0.0

我的pg版本是4.5.7。

升级到最新版本的pg(7.6.1(并更换后

pg.connect('pg://some:user@some.server', function(err, db){

带有

const connectionConfig = {
host: config.database.server,
port: config.database.port,
database: config.database.database,
user: config.database.username,
password: config.database.password
}
// get the connection from the connection pool
consumer.pool = new pg.Pool(connectionConfig)
consumer.pool.on('error', function(error) {
consumer.handleError();
return;
});
consumer.pool.connect(function(err, db){

问题已解决。

最新更新