【问题标题】:pg client.on('error' does not detect network disruptionpg client.on('error' 没有检测到网络中断
【发布时间】:2019-04-18 17:06:50
【问题描述】:

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

Relevant documentation:

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

当客户端处于连接、发送查询或断开连接的过程中时,它将从 PostgreSQL 服务器捕获错误并将其转发到相应的 client.connect client.query 或 client.end 回调/承诺;但是,客户端与 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 分钟来测试此功能。果然,连接断开了,但没有创建错误事件,控制台也没有记录任何内容。我也尝试关闭远程数据库,结果相同。

连接断开时如何收到错误消息?

【问题讨论】:

    标签: node.js postgresql node-postgres


    【解决方案1】:

    问题是旧版本的 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){
    

    问题已解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      相关资源
      最近更新 更多