gpt4 book ai didi

node.js - 使用 fork 进行错误处理

转载 作者:太空宇宙 更新时间:2023-11-03 23:09:50 26 4
gpt4 key购买 nike

在我的下面的代码中,错误没有被 Parent.js 捕获,而是由 processChildOne.js 抛出

// Parent.js

var cp = require('child_process');
var childOne = cp.fork('./processChildOne.js');
var childTwo = cp.fork('./processChildTwo.js');
childOne.on('message', function(m) {
// Receive results from child process
console.log('received1: ' + m);
});

// Send child process some work
childOne.send('First Fun');
childTwo.on('message', function(m) {
// Receive results from child process
console.log('received2: ' + m);
});

// Send child process some work
childTwo.send('Second Fun');


// processChildOne.js

process.on('message', function(m) {
var conn = mongoose.createConnection('mongodb://localhost:27017/DB');

conn.on('error', console.error.bind(console, 'connection error:'));
// Pass results back to parent process
process.send("Fun1 complete");
});


If processChildOne.js fails, how to throw error to parent so that processChildOne.js and processChildTwo.js both should be killed. How can we keep track of how many child processes have executed and how many still are in pending.
Thanks in advance

最佳答案

我认为发生了什么事,你的子进程并没有真正抛出错误,它写入console.error,所以在父进程中没有要捕获的“错误”。

您可能想在子项中显式抛出错误,或者任何库都会抛出错误。有了这个,我遇到了您提到的同样的问题。

node.js

var cp = require('child_process').fork('./p1.js');
cp.on('message', function(){
console.log('ya', arguments);
})

p1.js

console.error('bad stuff man')

但这至少按预期抛出了错误

p1.js

throw "bad stuff man";

这有助于捕获客户端中的错误并将其发送到父进程。

node.js

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

cp.on('message', function(){
console.log('error from client', arguments[0]);
})

p1.js
try{
throw "bad stuff man"
} catch(e){
process.send(e);
}

或者用于捕获客户端进程中的所有错误并将它们发送给父级..

p1.js

process.on('uncaughtException', function(e){
process.send(e);
})
throw "bad stuff man";

为了生成多个进程并跟踪数量,您应该能够执行此操作..

node.js

var numprocesses = 5, running = 0;

for(var i = numprocesses; i--;){

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

cp.on('message', function(pid){
console.log('error from client', pid, arguments[0]);
})

cp.on('exit', function(){
console.log('done');
running--;
console.log('number running', running, ', remaining', numprocesses-running);
})

running++;
}

p1.js

process.on('uncaughtException', function(e){
process.send(process.pid + ': ' + e);
})

// simulate this to be a long running process of random length
setTimeout(function(){}, Math.floor(Math.random()*10000));

throw "bad stuff man";

关于node.js - 使用 fork 进行错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18650474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com