Master 从 worker 收到一个空白的错误对象

Master receives a blank error object from the worker

这很有趣!发生什么事了?

故事到此结束。

问题在最后一点描述。主站未收到错误对象。可能是什么原因? worker 在将其发送给 master 之前完整地保存了错误对象。

上面的描述代码如下:

const cluster = require('cluster');
const Promise = require('bluebird');

if (cluster.isMaster) {

    console.log(`Master process is running`);
    let worker = cluster.fork(); // START A WORKER

    worker.on('message', (message) => { // LISTEN TO WORKER
        console.log(`Received from worker: ${message}`);
    });

    cluster.on('online', (worker) => { // LISTEN TO WHEN WORKER IS ONLINE
        worker.send('Hello worker'); // SEND HER A MESSAGE
    });
} else {
    process.on('message', async (message) => { // LISTEN TO HER MASTER
        try {
            let response = await calculate();
            process.send({
                status: true,
                trace: null,
                message: 'ok'
            });
        } catch (err) {
            process.send({
                status: false,
                trace: err, // ERR WAS HERE, BUT DOESN'T REACH MASTER!
                message: err.message
            });
        }
    });
}

function calculate() {
    try {
        throw new Error('This will take forever to compute');
    } catch (err) {
        return Promise.reject(err);
    }
}

如果您尝试 运行 上面的代码,这将是输出:

Master process is running
Received from worker: {"status":false,"trace":{},"message":"This will take forever to compute"}

正如我们所见,痕迹是空的!

根据 API doc,对于 process.send() 方法:

This function uses JSON.stringify() internally to serialize the message

所以,

const err = new Error('Message');
console.log(JSON.stringify(err)); // => {}

您可能想要做的是:

process.send({
    status: false,
    trace: err.stack,
    message: err.message
});