Processes do not exchange memory, so the only way to communicate is with strings, objects are serialized by JSON when sending, and JSON when receiving. Objects with an error are not serialized by default:
JSON.stringify(new Error())
"{}"
, JSON- , instanceof .
:
Error.prototype.toJSON = function() {
var ret = {
name: this.name,
message: this.message,
stack: this.stack,
__error__: true
};
Object.keys(this).forEach(function(key) {
if (!ret[key]) {
ret[key] = this[key];
}
}, this);
return ret;
};
:
JSON.stringify(new Error())
"{"name":"Error","message":"","stack":"Error\n at <anonymous>:2:16\n at Object.InjectedScript._evaluateOn (<anonymous>:762:137)\n at Object.InjectedScript._evaluateAndWrap (<anonymous>:695:34)\n at Object.InjectedScript.evaluate (<anonymous>:609:21)","__error__":true}"
:
function getMessageReceiver(fn) {
return function(data) {
var result = data;
if (data && data.__error__) {
result = new Error();
result.message = data.message;
result.stack = data.stack;
result.name = data.name;
Object.keys(data).forEach(function(key) {
if (!result[key]) {
result[key] = data[key];
}
});
}
return fn.call(this, result);
}
}
:
child.on('message', getMessageReceiver(function(data) {
if (data instanceof Error) {
console.log(data.stack);
} else {
}
}));