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 ?
I solved the problem by using child_process to create a thread for the script to execute in :
//main.js
var child_process = require('child_process');
var script = child_process.fork("scriptrunner.js");
script.on('error',function(err){
console.log("Thread module error " + JSON.stringify(err));
});
script.on('exit',function(code,signal){
if(code==null)
console.log("Script crashed");
else console.log("Script exited normally");
});
script.send("setTimeout(function(){ console.log('Async user script error');nonExistingFunction(); },2000);");
//scriptrunner.js
var contextify = require('contextify');
var context = {
console:{
log:function(msg){
console.log('Contextify : '+msg);
}
},
setTimeout:setTimeout
};
contextify(context);
process.on('message', function(js) {
try{
context.run(js);
}catch(err){
console.log("Catch sync user script error " + err);
}
});
So now if the script crashes it crash its own process and not the main node process. The downside is that I can't pass complex object (such as my context) between my main process and the script's thread, I need to find a workaround for that.