Javascript 异步函数错误处理中的膝关节炎功能
在我的Javascript 异步函数错误处理中的膝关节炎功能,javascript,node.js,error-handling,async-await,koa,Javascript,Node.js,Error Handling,Async Await,Koa,在我的app.js中,我有以下内容 app.use(async (ctx, next) => { try { await next() } catch (err) { ctx.status = 400 ctx.body = `Uh-oh: ${err.message}` console.log('Error handler:', err.message) } }); app.use(router()); 然后在routes中我定义了 rout
app.js
中,我有以下内容
app.use(async (ctx, next) => {
try {
await next()
} catch (err) {
ctx.status = 400
ctx.body = `Uh-oh: ${err.message}`
console.log('Error handler:', err.message)
}
});
app.use(router());
然后在routes
中我定义了
router.post('/', retrieve);
检索逻辑的结构如下所示
const retrieve = async ctx => {
Object.keys(ctx.request.files).forEach((key) => {
process(files[key]);
});
};
现在让我们假设我在retrieve
中抛出了一个错误
const retrieve = async ctx => {
throw new Error(`Error!`);
Object.keys(ctx.request.files).forEach((key) => {
process(files[key]);
});
};
这将正常工作,并一直冒泡到app.js
。但是,进程
函数也在使用异步
,如果我在那里抛出错误
const retrieve = async ctx => {
Object.keys(ctx.request.files).forEach((key) => {
process(files[key]);
});
};
const process = async (file) => {
throw new Error(`Error!`);
...
我得到以下错误
未处理的PromisejectionWarning:错误:错误
为什么我收到未处理的PromiserEjectionWarning?如何修复它并使其成为
进程中抛出的任何错误都会冒泡到app.js
?由于forEach循环不是异步的,错误会在执行后抛出,因此无法冒泡到app.js。现在有两种解决方案,您可以使用for
循环,或者映射承诺并等待它们全部解决。根据您的问题提供的示例代码:
用于按顺序调用进程
为什么ctx
async?当然还有未处理的拒绝<代码>进程
抛出,没有任何捕获it@JaromandaX我试图在try/catch中包装过程
,但同样的错误希望这对您有所帮助
const retrieve = async ctx => {
const ctxKeys = Object.keys(ctx.request.files);
for(let i = 0 ; i < ctxKeys.length ;++i){
await process(files[ctxKeys[i]]);
}
};
const retrieve = async ctx => {
await Promise.all(Object.keys(ctx.request.files).map(async (key) => {
await process(files[key]);
}));
};