I need to run unsafe JS script in node and be able to recover from errors. The script can use async functions so I use contextify instead of node built in VM module. The problem is that errors in async code in the script crash the node process.
Here is my test :
var contextify = require('contextify');
var context = {
console:{
log:function(msg){
console.log('Contextify : '+msg);
}
},
setTimeout:setTimeout
};
console.log("begin test");
contextify(context);
try{ // try to run unsafe script
//context.run("console.log('Sync user script error');nonExistingFunction();"); // works
context.run("setTimeout(function(){ console.log('Async user script error');nonExistingFunction(); },2000);"); // crash node process
}catch(err){
console.log("Recover sync user script error");
}
console.log("end test");
How can I catch async errors ?