即使在添加catch块之后,nodejs中的“ UnhandledPromiseRejectionWarning”

时间:2019-01-24 07:20:28

标签: javascript postgresql error-handling promise node-pg-pool

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

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

我尝试在诺言周围添加try catch块。在承诺内(在c​​atch块内),没有任何帮助。

以下是一些测试代码,这些代码可用来重现错误。

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.

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

1 个答案:

答案 0 :(得分:1)

捕获未拒绝的拒绝

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

catch块用于承诺,而不用于异步代码的回调版本。 因此,如果将引发任何错误,它将陷入if(err){//执行任何操作} 或

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

    console.log(results);

}).catch(function(err){

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

});
并在完成查询或发生任何错误后关闭池。