Skip to content

Commit b87bfd4

Browse files
adrian-niculescuedusperoni
authored andcommitted
fix(worker): hand worker_threads 'error' listeners an Error rebuilt from the thrown value
A worker_threads 'error' listener received the runtime's ErrorEvent, not an Error, and the message it carried was V8's "Uncaught Error: ..." text. The worker now reads the thrown value's name and message and forwards them with the error payload. The parent rebuilds an Error from them with the worker's stack, using the built-in constructor the name belongs to, and the parent's global error event carries that same Error when nothing handled it. The Worker shim cancels an error its listeners took with preventDefault() rather than through the truthy-return contract of onerror.
1 parent 4d8ae36 commit b87bfd4

16 files changed

Lines changed: 231 additions & 76 deletions

‎docs/ns-builtin-modules.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -732,12 +732,13 @@ resolvers read the same table differently:
732732
Seven rows are public today: `ns:module`, `ns:runtime`, `ns:util`,
733733
`node:module`, `node:url`, `node:util`, `node:worker_threads`.
734734
- The **internal require** builtins receive (previous section) is the only
735-
thing that can name an internal-only row. Five rows are marked that way:
735+
thing that can name an internal-only row. Six rows are marked that way:
736736
`internal/broadcast-channel`, `internal/dom-exception`, `internal/events`,
737-
`internal/message-channel`, `internal/message-event`. Their exports carry
738-
capabilities app code must not hold — listener-accounting hook keys, the
739-
error-reporter setter, base classes that must be the runtime's own rather
740-
than whatever a global currently names.
737+
`internal/message-channel`, `internal/message-event`,
738+
`internal/worker-events`. Their exports carry capabilities app code must not
739+
hold — listener-accounting hook keys, the error-reporter setter, the key a
740+
worker's rebuilt error travels under, base classes that must be the
741+
runtime's own rather than whatever a global currently names.
741742
- Builtins with **no row at all** (the intrinsics snapshot, the require
742743
factory, the console formatter) are invoked straight from their native call
743744
sites. There is no specifier that could reach them and nothing to mark.

‎docs/worker-threads.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ means deliberately unsupported.
5454
| `threadName` | shim | Always `undefined`. |
5555
| `workerData` | shim | Always `null` — see below. |
5656
| `parentPort` | shim | `null` on the main isolate. Inside a worker, a `MessagePort`-shaped `EventTarget` over the worker's existing parent channel: `postMessage` forwards to the global `postMessage`, `message`/`messageerror` are re-dispatched from the worker global scope, `start()` and `close()` are no-ops. It is **not** a real port: not transferable, no queue of its own. |
57-
| `Worker` | shim | A class over the runtime's global `Worker` with a small Node-style emitter (`on`/`once`/`off`/`removeListener`) for `message`, `messageerror`, `error`, `online` and `exit`. `postMessage(value, transfer)` and `terminate()` forward. `online` is emitted off a microtask after construction, not from the thread. `exit` (always code `0`) fires exactly once, when the thread has ended, whether the worker was terminated or ended by its own `close()`; `terminate()` resolves at the same point. Unsupported options throw a `TypeError` naming the option: `workerData`, `env`, `eval`, `transferList`, and `stdin`/`stdout`/`stderr` when explicitly truthy. The runtime's own `Worker` options (`androidPriority`) ride along untouched — the native constructor ignores keys it does not know. |
57+
| `Worker` | shim | A class over the runtime's global `Worker` with a small Node-style emitter (`on`/`once`/`off`/`removeListener`) for `message`, `messageerror`, `error`, `online` and `exit`. An `error` listener receives the worker's error rebuilt as an `Error` (see below). `postMessage(value, transfer)` and `terminate()` forward. `online` is emitted off a microtask after construction, not from the thread. `exit` (always code `0`) fires exactly once, when the thread has ended, whether the worker was terminated or ended by its own `close()`; `terminate()` resolves at the same point. Unsupported options throw a `TypeError` naming the option: `workerData`, `env`, `eval`, `transferList`, and `stdin`/`stdout`/`stderr` when explicitly truthy. The runtime's own `Worker` options (`androidPriority`) ride along untouched — the native constructor ignores keys it does not know. |
5858
| `postMessageToThread` | throws | `Error: postMessageToThread is not supported in this runtime`. |
5959
| `moveMessagePortToContext` | throws | `Error: moveMessagePortToContext is not supported in this runtime`. |
6060
| `locks` | absent | Web Locks are not implemented; the property does not exist. |
@@ -83,6 +83,22 @@ the code is `0` whichever way the worker ended — `terminate()`, its own
8383
delivers the notification, so a `terminate()` awaited from a dying isolate
8484
stays pending, as it does in Node when the parent process exits.
8585

86+
### An `error` listener receives a rebuilt `Error`
87+
88+
Node hands an `error` listener the worker's error deserialized on the parent.
89+
Only strings cross the isolate boundary here, so the parent rebuilds it from
90+
the thrown value's `name` and `message`, with the worker's stack as its
91+
`stack`. A built-in name (`TypeError`, `RangeError`, …) rebuilds with that
92+
constructor, so `instanceof` holds; any other name, a subclass's or a
93+
`DOMException`'s, is an own `name` on an `Error`. Other properties, such as a
94+
`code` or a `cause`, are not carried. A thrown value with no string `message`,
95+
such as a string or a number, arrives as an `Error` whose message is its string
96+
form, where Node hands over the value itself.
97+
98+
Once an `error` listener has received it, the error counts as handled and is
99+
not reported on the parent's global scope. With no `error` listener, the
100+
parent's global `error` event carries the same rebuilt `Error`.
101+
86102
### A worker error carries no `error` object, and the worker scope's `onerror` is not an event
87103

88104
An error the worker scope leaves unhandled reaches the parent as a real

‎eslint.config.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ const capturedStatics = [
3232

3333
// Captured constructors. A destructure from `primordials` shadows the global,
3434
// so these only fire on the unguarded reference.
35-
const restrictedGlobals = ['Date', 'FinalizationRegistry', 'Map', 'Number', 'Promise', 'Proxy', 'RangeError', 'Set', 'String', 'TypeError', 'Uint8Array', 'Uint32Array', 'WeakRef', 'WeakSet'].map((name) => ({
35+
const restrictedGlobals = ['Date', 'EvalError', 'FinalizationRegistry', 'Map', 'Number', 'Promise', 'Proxy', 'RangeError', 'ReferenceError', 'Set', 'String', 'SyntaxError', 'TypeError', 'Uint8Array', 'Uint32Array', 'URIError', 'WeakRef', 'WeakSet'].map((name) => ({
3636
name,
3737
message: `Destructure ${name} from primordials — builtins must not read intrinsics off globals user code can replace.`,
3838
}));
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
throw new DOMException("aborted in a worker", "AbortError");
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
var parentPort = require("node:worker_threads").parentPort;
22
parentPort.on("message", function () {
3-
throw new Error("thrown by a parentPort listener");
3+
throw new TypeError("thrown by a parentPort listener");
44
});

‎test-app/app/src/main/assets/app/tests/testMessaging.js‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,7 @@ describe("Messaging runtime edges", function () {
354354
expect(seen.length).toBe(1);
355355
expect(seen[0].message).toContain("boom from worker");
356356
expect(seen[0].error instanceof Error).toBe(true);
357+
expect(seen[0].error.message).toBe("boom from worker");
357358
worker.terminate();
358359
done();
359360
};
@@ -390,14 +391,29 @@ describe("Messaging runtime edges", function () {
390391
worker.on("error", function (error) {
391392
setTimeout(function () {
392393
removeEventListener("error", listener);
393-
expect(error.message).toContain("boom from worker");
394+
expect(error instanceof Error).toBe(true);
395+
expect(error.name).toBe("Error");
396+
expect(error.message).toBe("boom from worker");
397+
expect(error.stack).toContain("boom from worker");
394398
expect(globalErrors).toEqual([]);
395399
worker.terminate();
396400
done();
397401
}, SETTLE);
398402
});
399403
});
400404

405+
it("hands a node:worker_threads 'error' listener a thrown DOMException's name and message", function (done) {
406+
var wt = require("node:worker_threads");
407+
var worker = new wt.Worker("~/tests/messaging/domExceptionThrowingWorker.js");
408+
worker.on("error", function (error) {
409+
expect(error instanceof Error).toBe(true);
410+
expect(error.name).toBe("AbortError");
411+
expect(error.message).toBe("aborted in a worker");
412+
worker.terminate();
413+
done();
414+
});
415+
});
416+
401417
it("calls a node:worker_threads once listener once when an earlier listener emits again", function () {
402418
var wt = require("node:worker_threads");
403419
var worker = new wt.Worker("~/tests/eventLoopEchoWorker.js");
@@ -418,18 +434,20 @@ describe("Messaging runtime edges", function () {
418434
it("routes a throw from a parentPort listener to the parent's 'error' listeners", function (done) {
419435
var wt = require("node:worker_threads");
420436
var worker = new wt.Worker("~/tests/messaging/parentPortThrowingWorker.js");
421-
var messages = [];
437+
var errors = [];
422438
var finish = function () {
423-
expect(messages.length).toBe(1);
424-
expect(messages[0]).toContain("thrown by a parentPort listener");
439+
expect(errors.length).toBe(1);
440+
expect(errors[0] instanceof TypeError).toBe(true);
441+
expect(errors[0].name).toBe("TypeError");
442+
expect(errors[0].message).toBe("thrown by a parentPort listener");
425443
worker.terminate();
426444
done();
427445
};
428446
// Nothing else settles the spec when the error never arrives.
429447
var guard = setTimeout(finish, 10000);
430448
worker.on("error", function (error) {
431-
messages.push(error.message);
432-
if (messages.length === 1) {
449+
errors.push(error);
450+
if (errors.length === 1) {
433451
clearTimeout(guard);
434452
setTimeout(finish, SETTLE);
435453
}

‎test-app/runtime/src/main/cpp/CallbackHandlers.cpp‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1897,14 +1897,16 @@ void CallbackHandlers::CallWorkerScopeOnErrorHandle(Isolate *isolate, TryCatch &
18971897
// parent sees the handler's own error, and only that one.
18981898
if (innerTc.HasCaught()) {
18991899
ExtractTryCatchInfo(isolate, context, innerTc, message, source, stackTrace, lineno);
1900-
wrapper->PassUncaughtExceptionFromWorkerToParent(message, source, stackTrace, lineno);
1900+
wrapper->PassUncaughtExceptionFromWorkerToParent(message, source, stackTrace, lineno,
1901+
innerTc.Exception());
19011902
return;
19021903
}
19031904

19041905
// Unhandled at the worker scope - including when there is no scope
19051906
// handler at all - so it becomes the parent's error event.
19061907
ExtractTryCatchInfo(isolate, context, tc, message, source, stackTrace, lineno);
1907-
wrapper->PassUncaughtExceptionFromWorkerToParent(message, source, stackTrace, lineno);
1908+
wrapper->PassUncaughtExceptionFromWorkerToParent(message, source, stackTrace, lineno,
1909+
tc.Exception());
19081910
} catch (NativeScriptException &ex) {
19091911
ex.ReThrowToV8();
19101912
} catch (std::exception e) {

‎test-app/runtime/src/main/cpp/NativeScriptException.cpp‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -918,7 +918,9 @@ void PromiseRejectionTracker::Drain() {
918918
!workerWrapper->IsTerminating() && !workerWrapper->IsDisposed()) {
919919
string forwarded = message;
920920
string forwardedStack = stackTrace;
921+
Local<Value> forwardedValue = reason;
921922
if (!thrown.IsEmpty()) {
923+
forwardedValue = thrown;
922924
forwarded = ToDetailString(isolate, thrown);
923925
// The handler's own stack replaces the reason's; an accessor
924926
// that throws costs the stack, never the forward.
@@ -930,7 +932,7 @@ void PromiseRejectionTracker::Drain() {
930932
}
931933
}
932934
workerWrapper->PassUncaughtExceptionFromWorkerToParent(
933-
forwarded, "", forwardedStack, 0);
935+
forwarded, "", forwardedStack, 0, forwardedValue);
934936
}
935937
}
936938
} else {

‎test-app/runtime/src/main/cpp/NsBuiltinModules.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ constexpr Registration kRegistry[] = {
6868
{"internal/events", BuiltinId::kEvents, nullptr, true},
6969
{"internal/message-channel", BuiltinId::kMessageChannel, messaging::CreateBinding, true},
7070
{"internal/message-event", BuiltinId::kMessageEvent, nullptr, true},
71+
{"internal/worker-events", BuiltinId::kWorkerEvents, nullptr, true},
7172
};
7273

7374
constexpr const char* kDebugKey = "debug";

‎test-app/runtime/src/main/cpp/WorkerEvents.cpp‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -108,28 +108,28 @@ void WorkerEvents::EmitMessage(Isolate* isolate, Local<Object> receiver,
108108
(void)state->emitMessage.Get(isolate)->Call(context, receiver, 3, args).ToLocal(&result);
109109
}
110110

111-
bool WorkerEvents::EmitError(Isolate* isolate, Local<Object> receiver,
112-
const std::string& message, const std::string& source,
113-
const std::string& stackTrace, int lineNumber) {
111+
MaybeLocal<Value> WorkerEvents::EmitError(Isolate* isolate, Local<Object> receiver,
112+
const std::string& message, const std::string& source,
113+
const std::string& stackTrace, int lineNumber,
114+
const std::string& errorName,
115+
const std::string& errorMessage) {
114116
auto* state = RuntimeState::For<WorkerEventsState>(isolate);
115117
if (state == nullptr || state->emitError.IsEmpty()) {
116-
return false;
118+
return MaybeLocal<Value>();
117119
}
118120
Runtime* runtime = Runtime::TryGetRuntime(isolate);
119121
if (runtime == nullptr) {
120-
return false;
122+
return MaybeLocal<Value>();
121123
}
122124
Local<Context> context = runtime->GetContext();
123125

124-
Local<Value> args[4]{ArgConverter::ConvertToV8String(isolate, message),
126+
Local<Value> args[6]{ArgConverter::ConvertToV8String(isolate, message),
125127
ArgConverter::ConvertToV8String(isolate, source),
126128
Number::New(isolate, lineNumber),
127-
ArgConverter::ConvertToV8String(isolate, stackTrace)};
128-
Local<Value> result;
129-
if (!state->emitError.Get(isolate)->Call(context, receiver, 4, args).ToLocal(&result)) {
130-
return false;
131-
}
132-
return result->BooleanValue(isolate);
129+
ArgConverter::ConvertToV8String(isolate, stackTrace),
130+
ArgConverter::ConvertToV8String(isolate, errorName),
131+
ArgConverter::ConvertToV8String(isolate, errorMessage)};
132+
return state->emitError.Get(isolate)->Call(context, receiver, 6, args);
133133
}
134134

135135
void WorkerEvents::EmitEnded(Isolate* isolate, Local<Object> receiver) {

0 commit comments

Comments
 (0)