0

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

Roaders
  • 4,373
  • 8
  • 50
  • 71

1 Answers1

1

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?".

Community
  • 1
  • 1
  • Aha - thanks for that. I had not realised that I was actually just getting an empty object. It seems I will have to find another way of getting the error to the master. – Roaders Dec 05 '16 at 11:56