捕获从setInterval内部抛出的异常

时间:2018-03-22 08:01:56

标签: javascript node.js exception try-catch

捕获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();
    }

1 个答案:

答案 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();