How to send an error object from content script to background script?

I’m trying to send an error event object from the content script:

catch (error) {
    chrome.runtime.sendMessage(sender.id, error);
}

to the background script:

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    console.log(msg)
});

in order to log it there with the full stack trace and all the relevant data,
but it always arrives as undefined.
I tried to JSON.Stringify the error and send it in an object, but it arrives as an empty object.

From https://developer.chrome.com/docs/extensions/reference/runtime/: enter image description here

If I’m sending error.message and error.stack separately, creating a new Error object works fine:

let error = new Error();
error.message = msg.message
error.stack = msg.stack;

How can I send the error object and receive it as-is?

Answer

You can’t send the error “as-is”, since the error object will not survive the async call – it will have gone out of scope. The reason JSON.stringify doesn’t work is that the properties of the error are not enumerable because they belong to the error object’s prototype chain – they aren’t “owned properties”. See this answer for a discussion and solution. Basically, you need to copy the properties of the error object to a new object and pass that.

Leave a Reply

Your email address will not be published. Required fields are marked *