node.js - 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;
}
}
解决方案
尝试这个:
function cleanUpDatabase() {
return new Promise(async (resolve, reject) => {
let pool = await connection;
pool.query(`SELECT * FROM table1`);
resolve();
}).catch((error) => {
console.log(error);
});
}
推荐阅读
- css - 如何在 video.js 播放器中禁用框阴影和边框
- ssl - 错误 488 此处不可接受
- php - CodeIgniter BMI 计算器不工作
- ruby-on-rails - rails - 获取模型保存的 SQL
- mayavi - 在 mayavi 中沿流线检索值
- ruby-on-rails - 亚马逊 ec2 t2micro 实例上的 Elasticsearch
- r - 使用 R 在 GLM 回归中运行所有可能的交互
- angular - 当我是 Observable.interval 时如何允许函数 sortbydate()
- vba - 如何选择过滤器位置而不是它的实际名称?
- node.js - Mongoose 5.0.15 / MongoDB 3.6.4 转换为数组失败的值 [NaN,NaN]