1

What is the best way to catch the error thrown from inside the setInterval? Currently from the code below, on throwing the exception, the control does not reach 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();
    }
Jatt
  • 665
  • 2
  • 8
  • 20
  • Possible duplicate of [Catching exceptions in setInterval](https://stackoverflow.com/questions/24515558/catching-exceptions-in-setinterval) – vahdet Mar 22 '18 at 08:04
  • 1
    You don't catch exceptions from asynchronous callbacks. You don't use `setInterval` for timeouts. You don't use `setInterval` with promises. Have a look at [this](https://stackoverflow.com/q/37120240/1048572) for how to timeout your `downloadAndSaveDataFromRssUrls` call. – Bergi Mar 22 '18 at 08:12
  • @Bergi That was helpful – Jatt Mar 22 '18 at 09:50

1 Answers1

1

You need to move your try catch inside the 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();
Zenoo
  • 12,670
  • 4
  • 45
  • 69