diff --git a/packages/worker-utils/lib.test.ts b/packages/worker-utils/lib.test.ts index 705a6271..967f264e 100644 --- a/packages/worker-utils/lib.test.ts +++ b/packages/worker-utils/lib.test.ts @@ -7,5 +7,6 @@ test('module exports', () => { configureWorkerTask: lib.configureWorkerTask, createFsHelpers: lib.createFsHelpers, initTaskWorker: lib.initTaskWorker, + serializeWorkerError: lib.serializeWorkerError, }); }); diff --git a/packages/worker-utils/src/worker.ts b/packages/worker-utils/src/worker.ts index 60f882be..ba4a3378 100644 --- a/packages/worker-utils/src/worker.ts +++ b/packages/worker-utils/src/worker.ts @@ -42,7 +42,7 @@ export function initTaskWorker( 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)); }); @@ -75,3 +75,25 @@ function runWorkerTask( 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; + } +}