gpt4 book ai didi

javascript - 即使在添加 catch block 之后,nodejs 中的 "UnhandledPromiseRejectionWarning"

转载 作者:行者123 更新时间:2023-11-29 13:11:18 25 4
gpt4 key购买 nike

我正在为 postgres 数据库编写一个 api 服务器,并且正在测试一些压力情况。我正在使用模块 node-postgres 中的池,遇到了这个问题。

在启动服务器之前,我首先耗尽了所有的 postgers 连接。然后我尝试通过池运行查询。

我尝试在 promise 周围添加 try catch block 。在 promise 内(在 catch block 内),没有任何帮助。

以下是我重现错误的一些测试代码。

var pg = require('./node_modules/pg')

var pool = new pg.Pool(
{
user: "test",
password: "pass134",
host: "localhost",
database: "testdb",
port: 5432,
max: 32,
min: 16,
idleTimeoutMillis: 60000,
connectionTimeoutMillis: 10000
}
);

pool.on("error", function(err){

console.log("Error1: " + String(err));

});

pool.query("SELECT COUNT(*) FROM acal_cust", [])
.then(function(err, results){

console.log(err);
console.log(results);

}).catch(function(err){

console.log("Error2:" + String(err));

pool.end();

});

这是我运行代码时得到的结果。

Error2: error: sorry, too many clients already
(node:10422) UnhandledPromiseRejectionWarning: error: sorry, too many clients already
at Connection.parseE (/ext/node_modules/pg/lib/connection.js:554:11)
at Connection.parseMessage (/ext/node_modules/pg/lib/connection.js:381:17)
at Socket.<anonymous> (/ext/node_modules/pg/lib/connection.js:117:22)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:597:20)
(node:10422) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10422) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我想知道如何正确处理错误。这样它就不会被抛出。

最佳答案

catch Undled拒绝

process.on('unhandledRejection', error => {
// Will print "unhandledRejection err is not defined"
console.log('unhandledRejection', error.message);
});

catch block 用于 promises 而不是异步代码的回调版本。因此,如果抛出任何错误,它将被 if(err) {//do whatever} 捕获或

pool.query("SELECT COUNT(*) FROM acal_cust", []).then((results) => {

console.log(results);

}).catch(function(err){

console.log("Error:" + String(err));

});
并在完成查询或出现任何错误时关闭池。

关于javascript - 即使在添加 catch block 之后,nodejs 中的 "UnhandledPromiseRejectionWarning",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54341269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com