简体   繁体   中英

NodeJs: How to tell that a message sent from a worker to the master is an Error

I have a node app that uses a cluster of child processes. I am trying to handle errors in these children.

Children communicate with the master when they have finished their task by sending a message with the result of their work. If they encounter a problem they send an error:

var error = new Error("I am sorry MASTER, I failed");
const isError = error instanceof Error;
console.log(`throwing new error: ${error} ${isError}`);
process.send( error );

From this I get a console output:

throwing new error: I am sorry MASTER, I failed true

I then handle this in master:

const isError = message instanceof Error;
console.log(`Message: ${message} ${isError}`);
if(message instanceof Error)
{
    //handle error;
} else {
    //process message;
}

From this console log I get the following:

Message: [object Object] false

When the message is sent using the send() function instanceof no longer works.

How can I tell in the master that the message sent is an Error? I don't want to change the error at all as I don't want to put any constraints on the code in the child process, I want to just be able to send an error.

Thanks

https://nodejs.org/api/process.html#process_process_send_message_sendhandle_options_callback

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

let foo = new Error("ai caramba¡");
let bar = JSON.stringify(foo);

console.log(bar); // {}

You can find more information in the SO question "Is it not possible to stringify an Error using JSON.stringify?" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM