pg client.on('error' 没有检测到网络中断
Posted
技术标签:
【中文标题】pg client.on(\'error\' 没有检测到网络中断【英文标题】: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 分钟来测试此功能。果然,连接断开了,但没有创建错误事件,控制台也没有记录任何内容。我也尝试关闭远程数据库,结果相同。
连接断开时如何收到错误消息?
【问题讨论】:
【参考方案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)
问题已解决。
【讨论】:
以上是关于pg client.on('error' 没有检测到网络中断的主要内容,如果未能解决你的问题,请参考以下文章
PG::Error: SELECT DISTINCT, ORDER BY 表达式必须出现在选择列表中
PG::Error: 错误: 列 tutorials.tutorialcategory_id 不存在
ActionView::Template::Error (PG::UndefinedColumn: ERROR: 列posts.user_id 不存在