Skip to content
26 changes: 14 additions & 12 deletions NativeScript/runtime/DataWrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -583,20 +583,22 @@ class WorkerWrapper : public BaseDataWrapper {
void PassUncaughtExceptionFromWorkerToMain(v8::Local<v8::Context> context,
v8::TryCatch& tc,
bool async = true);
// Overload to pass a pre-built error payload when a TryCatch isn't available
// Note: this overload accepts only primitive types to avoid passing V8
// handles across isolates/threads.
void PassUncaughtExceptionFromWorkerToMain(const std::string& message,
const std::string& source,
const std::string& stackTrace,
int lineNumber, bool async = true);
// Overload to pass a pre-built error payload when a TryCatch isn't available.
// `thrown` is the value the worker threw, when there is one: its name and
// message are read here, on the worker's isolate, for the parent to rebuild
// the error from. Without it the parent's error is an Error carrying
// `message`. Only strings cross to the parent's isolate.
void PassUncaughtExceptionFromWorkerToMain(
const std::string& message, const std::string& source,
const std::string& stackTrace, int lineNumber, bool async = true,
v8::Local<v8::Value> thrown = v8::Local<v8::Value>());
// Forwards a drained unhandled promise rejection to the main isolate's
// worker.onerror, guarded against teardown. Shares marshaling with the
// exception overload above.
void PassUncaughtRejectionToMain(const std::string& message,
const std::string& source,
const std::string& stackTrace,
int lineNumber, bool async = true);
void PassUncaughtRejectionToMain(
const std::string& message, const std::string& source,
const std::string& stackTrace, int lineNumber, bool async = true,
v8::Local<v8::Value> thrown = v8::Local<v8::Value>());
void PostMessage(std::shared_ptr<worker::Message> message);
// WHATWG parity: the worker's implicit port message queue starts disabled;
// Worker.mm calls this once the entry script has finished evaluating
Expand Down Expand Up @@ -731,7 +733,7 @@ class WorkerWrapper : public BaseDataWrapper {
void ForwardErrorPayloadToMain(const std::string& message,
const std::string& source,
const std::string& stackTrace, int lineNumber,
bool async);
bool async, v8::Local<v8::Value> thrown);
};

} // namespace tns
Expand Down
2 changes: 1 addition & 1 deletion NativeScript/runtime/NativeScriptException.mm
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ static bool GiveWorkerOnErrorAChance(Isolate* isolate, Local<Context> context, L
}
std::string reasonMessage = tns::ToString(isolate_, forwarded);
worker->PassUncaughtRejectionToMain(reasonMessage, "Worker script",
forwardedStack, 1);
forwardedStack, 1, true, forwarded);
}
}
}
Expand Down
1 change: 1 addition & 0 deletions NativeScript/runtime/NsBuiltinModules.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ constexpr Registration kRegistry[] = {
{"internal/message-channel", BuiltinId::kMessageChannel,
messaging::CreateBinding, true},
{"internal/message-event", BuiltinId::kMessageEvent, nullptr, true},
{"internal/worker-events", BuiltinId::kWorkerEvents, nullptr, true},
};

// ns:runtime config keys. Each key defines its value domain and scope here;
Expand Down
22 changes: 13 additions & 9 deletions NativeScript/runtime/Worker.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,19 @@ class Worker {
static void InitEvents(v8::Local<v8::Context> context);

// Dispatches an `error` ErrorEvent on `receiver` (the Worker object, on the
// parent isolate) and returns whether a handler took ownership of it —
// either by returning truthy from the `onerror` attribute or by calling
// preventDefault(). Only primitives cross the isolate boundary, so the event
// carries no error object. A listener that throws leaves the exception
// pending for the caller's TryCatch and reports as unhandled. False before
// InitEvents has run.
static bool EmitError(v8::Isolate* isolate, v8::Local<v8::Object> receiver,
const std::string& message, const std::string& source,
const std::string& stackTrace, int lineNumber);
// parent isolate). Only primitives cross the isolate boundary, so the event
// carries no error object; the worker's error is rebuilt from `errorName`,
// `errorMessage` and `stackTrace`. Returns that error when no handler took
// ownership of the event, for the caller to report on the parent's global
// scope, and undefined when one did, either by returning truthy from the
// `onerror` attribute or by calling preventDefault(). Empty when a listener
// threw, which leaves the exception pending for the caller's TryCatch, and
// before InitEvents has run.
static v8::MaybeLocal<v8::Value> EmitError(
v8::Isolate* isolate, v8::Local<v8::Object> receiver,
const std::string& message, const std::string& source,
const std::string& stackTrace, int lineNumber,
v8::Local<v8::String> errorName, v8::Local<v8::String> errorMessage);

// Dispatches `nsworkerended` on `receiver` (the Worker object, on the parent
// isolate) once the worker's thread has finished. Internal and non-standard:
Expand Down
22 changes: 12 additions & 10 deletions NativeScript/runtime/Worker.mm
Original file line number Diff line number Diff line change
Expand Up @@ -785,21 +785,23 @@ throw NativeScriptException(
(void)state->emitMessage.Get(isolate)->Call(context, receiver, 3, args).ToLocal(&result);
}

bool Worker::EmitError(Isolate* isolate, Local<Object> receiver, const std::string& message,
const std::string& source, const std::string& stackTrace, int lineNumber) {
MaybeLocal<Value> Worker::EmitError(Isolate* isolate, Local<Object> receiver,
const std::string& message, const std::string& source,
const std::string& stackTrace, int lineNumber,
Local<v8::String> errorName, Local<v8::String> errorMessage) {
WorkerEventsState* state = Caches::StateFor<WorkerEventsState>(isolate);
if (state == nullptr || state->emitError.IsEmpty()) {
return false;
return MaybeLocal<Value>();
}
Local<Context> context = Caches::Get(isolate)->GetContext();

Local<Value> args[4]{tns::ToV8String(isolate, message), tns::ToV8String(isolate, source),
Number::New(isolate, lineNumber), tns::ToV8String(isolate, stackTrace)};
Local<Value> result;
if (!state->emitError.Get(isolate)->Call(context, receiver, 4, args).ToLocal(&result)) {
return false;
}
return result->BooleanValue(isolate);
Local<Value> args[6]{tns::ToV8String(isolate, message),
tns::ToV8String(isolate, source),
Number::New(isolate, lineNumber),
tns::ToV8String(isolate, stackTrace),
errorName,
errorMessage};
return state->emitError.Get(isolate)->Call(context, receiver, 6, args);
}

void Worker::EmitEnded(Isolate* isolate, Local<Object> receiver) {
Expand Down
128 changes: 99 additions & 29 deletions NativeScript/runtime/WorkerWrapper.mm
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,55 @@ static void PostToLoop(const std::shared_ptr<EventLoop>& loop, std::function<voi
}
}

// The `name` and `message` the parent rebuilds the worker's error from. They
// stay UTF-16 on the way, so both arrive exactly as thrown, embedded NULs and
// unpaired surrogates included.
struct ThrownErrorText {
std::u16string name = u"Error";
std::u16string message;
};

static std::u16string ToUtf16(Isolate* isolate, Local<v8::String> value) {
std::u16string result(value->Length(), u'\0');
value->WriteV2(isolate, 0, value->Length(), reinterpret_cast<uint16_t*>(result.data()));
return result;
}

static Local<v8::String> FromUtf16(Isolate* isolate, const std::u16string& value) {
return v8::String::NewFromTwoByte(isolate, reinterpret_cast<const uint16_t*>(value.data()),
v8::NewStringType::kNormal, static_cast<int>(value.size()))
.ToLocalChecked();
}

// Reads the text off the value the worker threw. An object's `name` and
// `message` are taken when they are strings, so an Error or a DOMException
// keeps both; anything else becomes an Error whose message is the value's
// string form. Either property may be a getter, and one that throws leaves the
// default in place.
static ThrownErrorText DescribeThrownValue(Isolate* isolate, Local<Context> context,
Local<Value> thrown) {
HandleScope handleScope(isolate);
TryCatch tc(isolate);
ThrownErrorText text;
Local<v8::String> detail;
if (thrown->ToDetailString(context).ToLocal(&detail)) {
text.message = ToUtf16(isolate, detail);
}
if (!thrown->IsObject() || thrown->IsFunction()) {
return text;
}
Local<Object> object = thrown.As<Object>();
Local<Value> value;
if (object->Get(context, tns::ToV8String(isolate, "name")).ToLocal(&value) && value->IsString()) {
text.name = ToUtf16(isolate, value.As<v8::String>());
}
if (object->Get(context, tns::ToV8String(isolate, "message")).ToLocal(&value) &&
value->IsString()) {
text.message = ToUtf16(isolate, value.As<v8::String>());
}
return text;
}

WorkerWrapper::WorkerWrapper(
v8::Isolate* mainIsolate,
std::function<void(v8::Isolate*, v8::Local<v8::Object> thiz, std::shared_ptr<worker::Message>)>
Expand Down Expand Up @@ -543,6 +592,8 @@ static void PostThreadEndedNotification(Isolate* mainIsolate, std::weak_ptr<Even
if (!reason.IsEmpty()) {
message = tns::ToString(isolate, reason);
if (reason->IsObject()) {
// `stack` may be an accessor that throws; that only costs the stack.
TryCatch stackTc(isolate);
Local<Object> reasonObj = reason.As<Object>();
Local<Value> stackVal;
if (reasonObj->Get(context, tns::ToV8String(isolate, "stack")).ToLocal(&stackVal) &&
Expand All @@ -551,7 +602,8 @@ static void PostThreadEndedNotification(Isolate* mainIsolate, std::weak_ptr<Even
}
}
}
this->PassUncaughtExceptionFromWorkerToMain(message, source, stackTrace, lineNumber, true);
this->PassUncaughtExceptionFromWorkerToMain(message, source, stackTrace, lineNumber, true,
reason);
}

void WorkerWrapper::PassUncaughtExceptionFromWorkerToMain(Local<Context> context, TryCatch& tc,
Expand Down Expand Up @@ -589,42 +641,56 @@ static void PostThreadEndedNotification(Isolate* mainIsolate, std::weak_ptr<Even

std::string stackTrace = "";

Local<Value> stackTraceVal = tc.StackTrace(context).FromMaybe(Local<Value>());
if (!stackTraceVal.IsEmpty()) {
Local<v8::String> stackTraceStr =
stackTraceVal->ToDetailString(context).FromMaybe(Local<v8::String>());
if (!stackTraceStr.IsEmpty()) {
stackTrace = tns::ToString(workerIsolate, stackTraceStr);
{
// `stack` may be an accessor. One that throws only costs the stack: caught
// here, its exception cannot replace the one `tc` holds.
TryCatch stackTc(workerIsolate);
Local<Value> stackTraceVal = tc.StackTrace(context).FromMaybe(Local<Value>());
if (!stackTraceVal.IsEmpty()) {
Local<v8::String> stackTraceStr =
stackTraceVal->ToDetailString(context).FromMaybe(Local<v8::String>());
if (!stackTraceStr.IsEmpty()) {
stackTrace = tns::ToString(workerIsolate, stackTraceStr);
}
}
}

this->ForwardErrorPayloadToMain(message, src, stackTrace, lineNumber, async);
this->ForwardErrorPayloadToMain(message, src, stackTrace, lineNumber, async, tc.Exception());
}

void WorkerWrapper::PassUncaughtExceptionFromWorkerToMain(const std::string& message,
const std::string& source,
const std::string& stackTrace,
int lineNumber, bool async) {
this->ForwardErrorPayloadToMain(message, source, stackTrace, lineNumber, async);
int lineNumber, bool async,
Local<Value> thrown) {
this->ForwardErrorPayloadToMain(message, source, stackTrace, lineNumber, async, thrown);
}

void WorkerWrapper::PassUncaughtRejectionToMain(const std::string& message,
const std::string& source,
const std::string& stackTrace, int lineNumber,
bool async) {
bool async, Local<Value> thrown) {
if (this->isTerminating_ || this->isDisposed_) {
return;
}
this->ForwardErrorPayloadToMain(message, source, stackTrace, lineNumber, async);
this->ForwardErrorPayloadToMain(message, source, stackTrace, lineNumber, async, thrown);
}

void WorkerWrapper::ForwardErrorPayloadToMain(const std::string& message, const std::string& source,
const std::string& stackTrace, int lineNumber,
bool async) {
bool async, Local<Value> thrown) {
std::shared_ptr<EventLoop> loop = mainLoop_.lock();
if (loop == nullptr) {
return;
}
// Read here, on the worker's isolate. A report with no thrown value, such
// as the heap-limit one made from inside a GC, touches no V8 handle.
std::optional<ThrownErrorText> thrownText;
if (!thrown.IsEmpty()) {
Isolate* workerIsolate = v8::Isolate::GetCurrent();
thrownText =
DescribeThrownValue(workerIsolate, Caches::Get(workerIsolate)->GetContext(), thrown);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// The task runs later, on the parent's loop, and this wrapper may be gone by
// then: a worker that reports and terminates is disposed on its own thread,
// after which the parent's finalizer deletes the wrapper as soon as the
Expand All @@ -635,7 +701,7 @@ static void PostThreadEndedNotification(Isolate* mainIsolate, std::weak_ptr<Even
std::shared_ptr<Persistent<Value>> poWorker = poWorker_;
PostToLoop(
loop,
[mainIsolate, poWorker, message, source, stackTrace, lineNumber]() {
[mainIsolate, poWorker, message, source, stackTrace, lineNumber, thrownText]() {
v8::Locker locker(mainIsolate);
Isolate::Scope isolate_scope(mainIsolate);
HandleScope handle_scope(mainIsolate);
Expand All @@ -644,28 +710,32 @@ static void PostThreadEndedNotification(Isolate* mainIsolate, std::weak_ptr<Even
return;
}

// Without a thrown value, the error is an Error carrying the report's
// message.
Local<v8::String> errorName = thrownText ? FromUtf16(mainIsolate, thrownText->name)
: tns::ToV8String(mainIsolate, "Error");
Local<v8::String> errorMessage = thrownText ? FromUtf16(mainIsolate, thrownText->message)
: tns::ToV8String(mainIsolate, message);

TryCatch tc(mainIsolate);
bool handled = Worker::EmitError(mainIsolate, worker.As<Object>(), message, source,
stackTrace, lineNumber);
Local<Value> error;
(void)Worker::EmitError(mainIsolate, worker.As<Object>(), message, source, stackTrace,
lineNumber, errorName, errorMessage)
.ToLocal(&error);
if (tc.HasCaught()) {
Local<Value> error = tc.Exception();
Log(@"%s", tns::ToString(mainIsolate, error).c_str());
mainIsolate->ThrowException(error);
Local<Value> thrown = tc.Exception();
Log(@"%s", tns::ToString(mainIsolate, thrown).c_str());
mainIsolate->ThrowException(thrown);
return;
}
if (handled) {
if (!error.IsEmpty() && error->IsUndefined()) {
// A handler took ownership of it.
return;
}
// HTML: an error the Worker object leaves unhandled is reported to the
// parent's global scope. Only primitives crossed the isolate boundary,
// so the error object is rebuilt from them here.
Local<Context> context = Caches::Get(mainIsolate)->GetContext();
Local<Value> error = v8::Exception::Error(tns::ToV8String(mainIsolate, message));
if (error->IsObject() && !stackTrace.empty()) {
(void)error.As<Object>()->Set(context, tns::ToV8String(mainIsolate, "stack"),
tns::ToV8String(mainIsolate, stackTrace));
}
if (!ErrorEvents::DispatchError(mainIsolate, error, message, stackTrace)) {
// parent's global scope.
if (error.IsEmpty() ||
!ErrorEvents::DispatchError(mainIsolate, error, message, stackTrace)) {
Log(@"Unhandled error in worker %s:%d: %s\n%s", source.c_str(), lineNumber,
message.c_str(), stackTrace.c_str());
}
Expand Down
Loading
Loading