在闭包的上下文中抛出错误没有到达catch子句
Throwing an Error inside the context of a closure is not reaching the catch clause
我在闭包的上下文中抛出了一个异常,并且无法捕获它。下面是一个简单的例子:
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);
相关文章:
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- errors with Javascript try catch
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- http/rxjs catch回调中的Angular 2重定向导致TypeError:无法读取属性'订阅'
- Knockout.js中带有if:子句的嵌套循环
- JSON.parse,已经在try/catch块中,仍然抛出语法错误
- 财产'catch'在类型'可观察<任意>'
- 错误处理try&catch+回调
- Catch无法读取null的属性
- 在try-catch块内的HTML文件中导入JavaScript文件
- javascript中的Catch X-Frame-Options错误
- Javascript:用if语句运行while循环,用子句随机生成内容
- if 子句在 JavaScript 中限定工作流
- Javascript Regex Catch Word
- 尝试在 if 子句中将变量从 js 发布到 php
- 在查询字符串中查找 where 子句
- 避免使用空的catch子句
- JavaScript catch子句作用域
- 在闭包的上下文中抛出错误没有到达catch子句
- 为什么catch子句有自己的词汇环境