【发布时间】:2019-04-18 17:06:50
【问题描述】:
我的应用程序连接到数据库并侦听事件,因此它可以执行事件。如果与数据库的连接断开,那么它应该能够通过consumer.db.on('error' 检测到它
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