Skip to content

Commit

Permalink
Serialize worker errors
Browse files Browse the repository at this point in the history
  • Loading branch information
timkendrick committed Dec 22, 2023
1 parent 691d34d commit d0e69aa
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/worker-utils/lib.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ test('module exports', () => {
configureWorkerTask: lib.configureWorkerTask,
createFsHelpers: lib.createFsHelpers,
initTaskWorker: lib.initTaskWorker,
serializeWorkerError: lib.serializeWorkerError,
});
});
24 changes: 23 additions & 1 deletion packages/worker-utils/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export function initTaskWorker<I, O>(
runWorkerTask(task, data, runner)
.then(
(result) => ({ success: true as const, value: result }),
(error) => ({ success: false as const, error: error.message }),
(error) => ({ success: false as const, error: serializeWorkerError(error) }),
)
.then((output) => channel.postMessage(output));
});
Expand Down Expand Up @@ -75,3 +75,25 @@ function runWorkerTask<I, O>(
return Promise.reject(error);
}
}

export function serializeWorkerError(error: unknown): Error {
if (error instanceof Error) {
if (isSerializable(error)) return error;
const { name, message, stack, ...properties } = error;
return Object.assign(new Error(message), {
name,
stack,
...properties,
});
}
return new Error(String(error));
}

function isSerializable(value: unknown): boolean {
try {
structuredClone(value);
return true;
} catch {
return false;
}
}

0 comments on commit d0e69aa

Please sign in to comment.