如何捕获未犯错误的迭代号码?
我有一个在异步函数内部运行给定功能calculatingfn()
的循环,该函数倾向于通过丢弃未知的错误而失败。
(async ()=>{
const data=[...] // some data
for(i=0;i<data.length;i++){
await calculatingFn(data[i]); // throws error sometimes
}
})()
如果循环失败,则整个程序将停止执行,就像我希望的那样。但是,我想安装记录最后一个迭代号码,以便可以在留下的地方摘下。因此,我想到现在捕获错误
(async ()=>{
// the rest of the code
})().catch(err=>console.log(err))
而不是记录错误消息,我希望获得最后的迭代编号,因此
(async ()=>
const data=[...]
for(i=0;i<data.length;i++){
await calculatingFn(data[i]);
}
})().catch((err,i)=>console.log(i)) // accessing i inside the catch block
我如何在Catchblock内访问I,Iteration编号。请注意,错误是由我正在使用的库的内部流程抛出的。
I have a for loop inside an async function that runs a given a function calculatingFn()
that has a tendency to fail by throwing an uncaught error.
(async ()=>{
const data=[...] // some data
for(i=0;i<data.length;i++){
await calculatingFn(data[i]); // throws error sometimes
}
})()
If the loop fails, the whole program stops executing, as I expect it to. However I want to console log the last iteration number so that I can pick off where I left it. So I thought of catching the error
(async ()=>{
// the rest of the code
})().catch(err=>console.log(err))
Now instead of logging the error message, I wish to get the last iteration number like so
(async ()=>
const data=[...]
for(i=0;i<data.length;i++){
await calculatingFn(data[i]);
}
})().catch((err,i)=>console.log(i)) // accessing i inside the catch block
How can I access i, the iteration number, inside the catchblock. Note that the error is thrown by internal processes of the libraries I am using.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与其从循环外部捕获错误,捕获循环内部的错误,然后执行您想要的操作,并且在您的语句之后将恢复循环。
instead of catch error from outside of the loop catch the error inside the loop then do what you want and the loop will resumed after your statement.
由于它是
async
函数,您可以在功能调用周围添加一个尝试...同时记录迭代和错误。如果您希望自己的最高水平能够看到它,我建议您再次扔它。
Since it's an
async
function you can add a try ... catch block around the function call, then log the iteration and error at the same time.I'd suggest you throw this again if you wish your top level to be able to see it.