如何在节点中生成和处理子进程中生成的错误

时间:2017-05-19 19:26:16

标签: javascript node.js child-process spawn

我正在使用节点child_process来生成系统中的进程。我可以使用datastdinstderr和{{data上的回调来控制来自errorend等的exit输出1}}事件。

问题在于,当我像这里一样加载可执行文件时:

/**
 * Load model in memory
 */
Executable.prototype.load = function() {
    var self=this;
    this.onExitCallback=null;
    this.onDataCallback=null;
    this.onErrorCallback=null;
    return new Promise(function(resolve, reject) {
        self.emitDeferred(EVENT_LOAD_START);
        if( self.child ) {
            self.emitDeferred(EVENT_LOAD_DONE);
            return resolve(true);
        }
        self.onErrorCallback = function(error) {
            return reject(error);
        }
        var args =[
            '-input',
            '-'
        ];
        if( self._options.debug) console.log("load",args);
        self.child=self.exec('runner', self._options.bin, args, self._options.child);
        if(self._options.debug) self.child.stdout.pipe(process.stdout);
        self.emitDeferred(EVENT_LOAD_DONE);
        return resolve(true);
    });
}//load

我在error回调中收到错误,我会调用resolvereject,因为后者将由onErrorCallback触发,而第一个将在产生后立即触发,而我需要在保持resolve的同时避开onErrorCallback

这是我的exec代码:

    /**
     * Execute child process
     */
    this.exec = function(name,command,params,options) {
        var self=this;
        var _options = { detached: false };
        for (var attrname in options) { _options[attrname] = options[attrname]; }

        var created_time= ( new Date() ).toISOString();
        var task = require('child_process').spawn(command, params, _options);
        task.stdout.on('data', function(_data) {
            if( self.onDataCallback ) self.onDataCallback.apply(self,[ new Buffer(_data,'utf-8').toString() ] );
        });
        task.on('error', function(error) {
            if(self._options.debug) console.error("exec:%s pid:%d error:\n",name,task.pid,error);
            if( self.onErrorCallback ) self.onErrorCallback.apply(self,[error]);
        });
        task.on('uncaughtException', function (error) {
            if(self._options.debug) console.error("exec:%s pid:%s uncaughtException:\n",name,task.pid,error);
            if( self.onErrorCallback ) self.onErrorCallback.apply(self,[error]);
        });
        task.stdout.on('end', function(data) {
            if(self._options.debug) console.log("exec:%s end.",name);
        });
        task.stderr.on('data', function(data) {
            //if(self._options.debug) console.log("exec:%s stderr:%s",name,data);
            //if(!data) task.kill('SIGINT');
        });
        task.on('close', (code, signal) => {
            if(self._options.debug) console.warn('task:%s pid:%s terminated due to receipt of signal:%s',name,task.pid,signal);
        });
        task.on('exit', function(code) {
            if(self._options.debug) console.log("exec:%s exit.",name);
            if (code != null && code != 0) {
                var error=new Error();
                error.description= command + ' ' + params.join(' ');
                error.code=code;
                if(self._options.debug) console.error("exec:%s pid:%d error:\n",name,task.pid,error);
                task.kill('SIGINT');
                if( self.onExitCallback ) self.onExitCallback.apply(self,[error]);
            } else {
                // at exit explicitly kill exited task
                task.kill('SIGINT');
                if( self.onExitCallback ) self.onExitCallback.apply(self);
            }
        });
        return task;
    }//exec

send代码将原始数据发送到正在运行的子进程:

    /**
     * Send data to child process
     */
    this.send = function(data) {
        this.child.stdin.setEncoding('utf-8');
        this.child.stdin.write( data + '\r\n' );
    }//send

所以要测试它就像

myExecutable.load()
.then(done => {
    console.log("loaded %d", done);
})
.catch(error => {
    console.error("error",error);
});

1 个答案:

答案 0 :(得分:1)

您可以使用try{}catch(err){}机制,您可以将onErrorCallback触发的代码放入catch中,从而避免解决问题,同时保持onErrorCallback不变。