Skip to content

Commit

Permalink
Fix the error serialization for the inter-thread messaging (#641)
Browse files Browse the repository at this point in the history
  • Loading branch information
whitphx authored Oct 10, 2023
1 parent 5c1ebf0 commit 1b90949
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions packages/kernel/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -472,11 +472,21 @@ self.onmessage = async (event: MessageEvent<InMessage>): Promise<void> => {
} catch (error) {
console.error(error);

// The `error` object may contain non-serializable properties such as function,
if (!(error instanceof Error)) {
throw error;
}

// The `error` object may contain non-serializable properties such as function (for example Pyodide.FS.ErrnoError which has a `.setErrno` function),
// so it must be converted to a plain object before sending it to the main thread.
// Otherwise, the following error will be thrown:
// `Uncaught (in promise) DOMException: Failed to execute 'postMessage' on 'MessagePort': #<Object> could not be cloned.`
const cloneableError = JSON.parse(JSON.stringify(error)); // Ref: https://stackoverflow.com/a/42376465/13103190
// Also, the JSON.stringify() and JSON.parse() approach like https://stackoverflow.com/a/42376465/13103190
// does not work for Error objects because the Error object is not enumerable.
// So we use the following approach to clone the Error object.
const cloneableError = new Error(error.message);
cloneableError.name = error.name;
cloneableError.stack = error.stack;

messagePort.postMessage({
type: "reply",
error: cloneableError,
Expand Down

0 comments on commit 1b90949

Please sign in to comment.