在闭包的上下文中抛出错误没有到达catch子句

Throwing an Error inside the context of a closure is not reaching the catch clause

本文关键字:子句 catch 错误 出错 闭包 上下文      更新时间:2023-09-26

我在闭包的上下文中抛出了一个异常,并且无法捕获它。下面是一个简单的例子:

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

它永远不会进入catch子句,并导致我的节点进程终止。这里也是一样:

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

我的实际例子更接近于这样:

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

我需要try/catch作为安全措施。目前,这种行为导致我的节点进程终止。如何捕获异常?

你的问题有一个答案:https://stackoverflow.com/a/10337225/5111146

解决方法是将try catch移到超时时调用的方法中

如果错误将是一致的,并且可以在vm上下文之外的代码中处理,则可以使用未处理异常和拒绝的全局处理程序来捕获这些错误。

process.on('unhandledRejection', console.log);
process.on('uncaughtException',  console.log);