SetTimeout processing error

A simple try-catch question for a function in setTimeout

try {
    setTimeout(function () {
        throw new Error('error!');
    }, 300)
} catch (e) {
    console.log('eeee!')
    console.log(e)
}

Why does catch-block not work?

What can I read about this?

PS: The question is about the possibility of handling such errors. Do not reply about promises

+4
source share
3 answers

The functions planned to start with setTimeoutare executed in the main loop, outside the main code that created them.

To handle errors, put try-catchinside the handler setTimeout:

setTimeout(function () {
  try {
    throw new Error('error!');
  } catch (e) {
    console.error(e);
  }
}, 300)

If you need access to an object Errorfrom a block called setTimeout, use Promises :

const promise = new Promise((resolve, reject) => {
  setTimeout(function () {
    try {
      throw new Error('error!');
    } catch (e) {
      reject(e)
    }
  }, 300)
})

promise
  .then(result => console.log("Ok " + result))
  .catch(error => console.error("Ouch " + error))

- Promise. delay(ms) :

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

delay(300).then(myFunction).catch(handleError)
+8

catch setTimeout, , . ,

setTimeout(function () {
  try {
    throw new Error('error!');
  } catch (e) {
    console.log('eeee!');
    console.log(e);
  }
}, 300);
+1

Node.js doc.

, setTimeout() , try { } catch(err) { } . , Node.js.

However, if you want to handle errors in a function callback setTimeout(), you can listen to them using the processglobal EventEmitter object

process.on('uncaughtException', function(err){
  console.log(err)   
})
+1
source

Source: https://habr.com/ru/post/1665538/


All Articles