Search code examples
node.jschild-processspawn

Detecting python exceptions in Node child_process


I've noticed that when I spawn a python script in Node.js using the child_process spawn() method, I can't catch exceptions.

Here's a simple example to illustrate:

index.js:


const spawn = require('child_process').spawn;

(() => {
    const py = spawn('python', ['../pyfun/main.py']);

    py.stdout.on('data', function(data){
        console.log(data.toString());
    });

    py.stdout.on('end', function(){
        console.log('Finished');
    });

    py.stdout.on('error', function(){
        console.log('* Error');
    });

    py.on('error', (err) => {
        console.error('**', err);
    });

    py.stderr.on('error', (err) => {
        console.log('*** Error', error);
    })
})();

main.py:

def main():
    print('Hello')
    raise ValueError('Python Error')

if __name__ == '__main__':
    main()

The output is

Hello // <-- from python

Finished // <-- from Node

I'm getting the hello from the Python script, but I'm unable to pick up the error. This is also the case if I use raise Exception('error') in the python script too.

Any insight appreciated.


Solution

  • Add a handler for py.on('exit', code => {}) and if the code is nonzero, the error has been dumped to stderr which you can access via py.stderr.on('data', data => {})