簡體   English   中英

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

[英]"UnhandledPromiseRejectionWarning" in nodejs even after adding catch block

我正在為 postgres 數據庫編寫 api 服務器,並且正在測試一些壓力情況。 我正在使用模塊 node-postgres 中的一個池,並遇到了這個問題。

在啟動服務器之前,我首先用盡了所有的 postgers 連接。 然后我嘗試通過池運行查詢。

我嘗試在承諾周圍添加 try catch 塊。 在承諾內(在 catch 塊內),沒有任何幫助。

以下是我重現錯誤的一些測試代碼。

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.

我想知道如何正確處理錯誤。 這樣它就不會被拋出。

捕獲未處理的拒絕

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

catch 塊是用於承諾而不是用於異步代碼的回調版本。 因此,如果將拋出任何錯誤,它將被捕獲在 if(err) {//do nothing} 或

 pool.query("SELECT COUNT(*) FROM acal_cust", []).then((results) => { console.log(results); }).catch(function(err){ console.log("Error:" + String(err)); });
並在完成查詢或任何錯誤后關閉池。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM