0

我需要在节点中运行不安全的 JS 脚本并能够从错误中恢复。该脚本可以使用异步函数,因此我使用 contextify 而不是 VM 模块中内置的节点。问题是脚本中异步代码中的错误会使节点进程崩溃。

这是我的测试:

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");

如何捕获异步错误?

4

1 回答 1

0

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.

于 2014-09-30T10:21:16.800 回答