Domanda

I have the below code

// Parent.js

var cp = require('child_process');
var child = cp.fork('./pChild.js');

child.on('message', function(m) {
    // Receive results from child process
    console.log('received: ' + m);
});

// Send child process some work
child.send('First Fun');
// pChild.js

process.on('message', function(m) {
console.log("Helloooooooooo from pChild.js")
// Pass results back to parent process
process.send("Fun1 complete");
});

How to handle error in parent thrown from pChild.js and kill the process?

È stato utile?

Soluzione

Unhandled errors in the child process will cause it to exit, which will emit the 'exit' event on the child object.

child.on('exit', function (code, signal) {
    console.log('Child exited:', code, signal);
});

If the error is handled within the child, it can be sent as another message:

// in pChild.js
/* ... */.on('error', function (error) {
    process.send({ error: error.message || error });
});

Updated answer

On child

process.on('uncaughtException', (err) => {
    process.send({isError: true});
});

On master

 master.on('message',({isError, data})=>{
    if(isError) {
         master.kill('SIGINT');
         return;
    }
    console.log('message from child', data);
    master.kill('SIGINT');
 });
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top