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

pg client.on('error' does not detect network disruption

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

检测到它

Relevant documentation:

client.on('error', (err: Error) => void) => void

When the client is in the process of connecting, dispatching a query, or disconnecting it will catch and foward errors from the PostgreSQL server to the respective client.connect client.query or client.end callback/promise; however, the client maintains a long-lived connection to the PostgreSQL back-end and due to network partitions, back-end crashes, fail-overs, etc the client can (and over a long enough time period will) eventually be disconnected while it is idle. To handle this you may want to attach an error listener to a client to catch errors. Here's a contrived example:

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){

问题已解决。