首页 > 解决方案 > Node.js 错误链接未传播到调用函数

问题描述

我有一个每 5 秒运行一次的 Nodejs cron 作业:

cron.schedule("*/5 * * * * * *", async function() {    //Every 5 seconds
    try{

        await cleanUpDatabase()
       
    }
    catch(err){
       console.log(err)
       console.trace(err.lineNumber)
    }
});

async function cleanUpDatabase(){
    let pool = await connection;

    pool.query(`SELECT * FROM table1`)
}

我的数据库中没有名为 table1 的表。我希望第二个函数产生错误

但是根据我对 try catch 块的理解,因为调用函数的cleanUpDatabase函数具有 catch 语句,即使cleanUpDatabase函数上没有 try catch ,它也应该捕获错误。但是它没有抓住它

在我的快速应用程序中,我有一个显示所有未处理拒绝的函数:

process.on('unhandledRejection', (error, p) => { //I added this so that I can console log the unhandled rejection and where it is coming from. Before this I would just get UnhandledPromiseRejectionWarning: Unhandled promise rejection without knowing which promise was not handled
    console.log('=== UNHANDLED REJECTION ==='); // Not good to have unhandled promise rejection in code. This will just help me locate it incase here is one
    console.dir(error.stack);
});

此函数正在捕获错误。这意味着错误未得到处理。我得到的错误是:

=== UNHANDLED REJECTION === "RequestError: Invalid object name 'table1'.\n"

为什么父函数无法处理错误?

编辑1:

即使这样也行不通。我现在真的很困惑

async function cleanUpDatabase(){
    try{
        let pool = await connection;
        pool.query(`SELECT * FROM table1`)
    }
    catch(err){
        throw err;
    }
    
}

标签: node.js

解决方案


尝试这个:

function cleanUpDatabase() {
    return new Promise(async (resolve, reject) => {
        let pool = await connection;
        pool.query(`SELECT * FROM table1`);
        resolve();
    }).catch((error) => { 
        console.log(error); 
    });
}

推荐阅读