捕获setInterval
内部错误的最佳方法是什么?目前,从下面的代码中,抛出异常后,控件无法到达catch
。
try {
timer = setInterval(() => {
if (moment().diff(lastProcessTime, 'minute') >= 2) {
// Taking too long!
clearInterval(timer);
throw new Error({ code: -1, message: `Taking too long to response:: ${urls[0]}` });
}
}, 1000);
await c.downloadAndSaveDataFromRssUrls(configs, urls);
clearInterval(timer);
return Promise.resolve();
} catch (err) {
clearInterval(timer);
console.log(err);
return Promise.resolve();
}
答案 0 :(得分:1)
您需要将try catch
移到setInterval
内
:
function greet() {
let i = setInterval(() => {
try {
if (Math.random() * 100 > 5) {
clearInterval(i);
throw new Error("Number is greater than 5");
}
} catch (err) {
console.log('Hello')
console.log(err);
}
}, 1000);
}
greet();