【发布时间】:2022-01-12 15:49:36
【问题描述】:
我正在实现一段代码,该代码通过项目的构建并检查是否有多个带有featured: true 的页面。如果是这种情况,我想抛出一个错误,这样管道中的qa 作业就会失败。一切都会很好,但我得到了:
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()
这是我的代码:
/* eslint-disable no-restricted-syntax */
const fs = require('fs');
const findInDir = require('./utils/findInDir');
(async () => {
const dir = './public/page-data/blog';
const fileRegex = /.*/;
const allFiles = findInDir(dir, fileRegex);
let result = 0;
for (const file of allFiles) {
try {
// eslint-disable-next-line no-await-in-loop
const data = await fs.promises.readFile(file);
const obj = JSON.parse(data);
if (obj.result.pageContext.featured === true) {
result += 1;
}
} catch (err) {
// noop
}
}
if (result > 1) {
throw new Error('There are multiple featured blog posts, please fix.');
}
})();
如何在异步函数中抛出错误?
【问题讨论】:
-
您正在在异步函数中抛出错误,这正是您看到该消息的原因。该消息说您在异步函数中抛出了一个错误,并没有在任何地方处理。
-
你的外部
async包装器根本没有错误处理,所以如果你让一个被拒绝的承诺到达那里,那么你会得到UnhandlePromiseRejectionWarning。要么在所有错误退出您的async函数包装器之前捕获所有错误,要么在该包装器上进行错误处理。 -
另外
findInDir可能会抛出错误 -
“这样管道中的
qa作业会失败”是什么意思?那份工作如何调用你的脚本?你需要做什么才能让它失败?
标签: javascript node.js asynchronous