@@ -389,12 +389,10 @@ void Worker::fireEarlyMessages(Zig::GlobalObject* workerGlobalObject)
389389 }
390390}
391391
392- void Worker::dispatchError (WTF::String message)
392+ void Worker::dispatchErrorWithMessage (WTF::String message)
393393{
394-
395394 auto * ctx = scriptExecutionContext ();
396- if (!ctx)
397- return ;
395+ if (!ctx) return ;
398396
399397 ScriptExecutionContext::postTaskTo (ctx->identifier (), [protectedThis = Ref { *this }, message = message.isolatedCopy ()](ScriptExecutionContext& context) -> void {
400398 ErrorEvent::Init init;
@@ -404,6 +402,27 @@ void Worker::dispatchError(WTF::String message)
404402 protectedThis->dispatchEvent (event);
405403 });
406404}
405+
406+ bool Worker::dispatchErrorWithValue (Zig::GlobalObject* workerGlobalObject, JSValue value)
407+ {
408+ auto * ctx = scriptExecutionContext ();
409+ if (!ctx) return false ;
410+ auto serialized = SerializedScriptValue::create (*workerGlobalObject, value, SerializationForStorage::No, SerializationErrorMode::NonThrowing);
411+ if (!serialized) return false ;
412+
413+ ScriptExecutionContext::postTaskTo (ctx->identifier (), [protectedThis = Ref { *this }, serialized](ScriptExecutionContext& context) -> void {
414+ auto * globalObject = context.globalObject ();
415+ ErrorEvent::Init init;
416+ JSValue deserialized = serialized->deserialize (*globalObject, globalObject, SerializationErrorMode::NonThrowing);
417+ if (!deserialized) return ;
418+ init.error = deserialized;
419+
420+ auto event = ErrorEvent::create (eventNames ().errorEvent , init, EventIsTrusted::Yes);
421+ protectedThis->dispatchEvent (event);
422+ });
423+ return true ;
424+ }
425+
407426void Worker::dispatchExit (int32_t exitCode)
408427{
409428 auto * ctx = scriptExecutionContext ();
@@ -483,7 +502,16 @@ extern "C" void WebWorker__dispatchError(Zig::GlobalObject* globalObject, Worker
483502 init.bubbles = false ;
484503
485504 globalObject->globalEventScope ->dispatchEvent (ErrorEvent::create (eventNames ().errorEvent , init, EventIsTrusted::Yes));
486- worker->dispatchError (message.toWTFString (BunString::ZeroCopy));
505+ switch (worker->options ().kind ) {
506+ case WorkerOptions::Kind::Web:
507+ return worker->dispatchErrorWithMessage (message.toWTFString (BunString::ZeroCopy));
508+ case WorkerOptions::Kind::Node:
509+ if (!worker->dispatchErrorWithValue (globalObject, error)) {
510+ // If serialization threw an error, use the string instead
511+ worker->dispatchErrorWithMessage (message.toWTFString (BunString::ZeroCopy));
512+ }
513+ return ;
514+ }
487515}
488516
489517extern " C" WebCore::Worker* WebWorker__getParentWorker (void * bunVM);
0 commit comments