0

I am throwing an exception in the context of closure and can't catch it. Here is a trivial example.

try{
  setTimeout(function(){ throw Error() },100)
}
catch(error)
{
   console.log("YES",error);
}

It never makes it to the catch clause and causes my node process to terminate. Same issue here:

try{
  setTimeout(function(){undefinedMethod() },100)
}
catch(error)
{
   console.log("YES",error);
}

My real example is closer to this:

 try{
   var ctx={setTimeout:setTimeout};
   require('vm').runInNewContext("setTimeout(function(){undefinedMethod() },100)",ctx)  
 }
 catch(error)
 {
   console.log(error);
 }

I need the try/catch as safety measure. Currently this behaviour causes my node process to terminate. How can I catch the exception?

Stan Wiechers
  • 1,962
  • 27
  • 45

2 Answers2

2

There's an answer to your question here: https://stackoverflow.com/a/10337225/5111146

The solution is too move the try catch into the method called on timeout.

Community
  • 1
  • 1
James Brierley
  • 4,630
  • 1
  • 20
  • 39
0

If the error is going to be consistent and can be handled in the code outside the vm context, global handler for unhandled exception and rejection can be used catch these errors.

process.on('unhandledRejection', console.log);
process.on('uncaughtException',  console.log);
par
  • 817
  • 8
  • 21