Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat: uncaughtErrorPolicy config, deprecate discardUncaughtJsExceptions
Replace the never-released crashOnUncaughtJsExceptions flag with the
cross-runtime uncaughtErrorPolicy contract:

  { "uncaughtErrorPolicy": "report" }  // default: report, keep running
  { "uncaughtErrorPolicy": "throw" }   // rethrow unprevented errors natively

"throw" keeps the same mechanics (deferred NativeScriptFatalJSException
from a clean scope-free frame, JS stack in reason/userInfo) under an
honest name: it is a throw, not a crash guarantee - the app terminates
only if no native handler catches it. Unknown values warn once and fall
back to "report".

discardUncaughtJsExceptions is deprecated but still honored in full for
now (routes to __onDiscardedError, skips the fatal log, suppresses the
throw policy); it logs a one-time deprecation warning pointing at
preventDefault() and uncaughtErrorPolicy.
  • Loading branch information
edusperoni committed Jul 23, 2026
commit 05389dd85429548fa869ec0fe0d8072698693906
2 changes: 1 addition & 1 deletion NativeScript/runtime/ArgConverter.mm
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@
}

// Unbranded: report exactly once through the uncaught path (error-event
// dispatch + shims + log; honors crashOnUncaughtJsExceptions). This is the
// dispatch + shims + log; honors uncaughtErrorPolicy). This is the
// path for the Assert-hardened sites that today never reach the message
// listener at all.
Local<v8::Message> message = tc.Message();
Expand Down
37 changes: 31 additions & 6 deletions NativeScript/runtime/NativeScriptException.mm
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,20 @@ static void ScheduleDeferredThrow(Isolate* isolate, NSException* e) {
}
}
Local<Value> handler;
// Deprecated: still honored in full (selects the __onDiscardedError callback
// and skips the fatal log), but new code should handle errors with an
// error/unhandledrejection listener calling preventDefault(), or set
// uncaughtErrorPolicy.
id value = Runtime::GetAppConfigValue("discardUncaughtJsExceptions");
bool isDiscarded = value ? [value boolValue] : false;
if (isDiscarded) {
static std::once_flag warnedDeprecated;
std::call_once(warnedDeprecated, []() {
Log(@"NativeScript: \"discardUncaughtJsExceptions\" is deprecated. Handle errors with a "
@"globalThis \"error\"/\"unhandledrejection\" listener calling preventDefault(), or "
@"configure \"uncaughtErrorPolicy\".");
});
}

std::string cbName = isDiscarded ? "__onDiscardedError" : "__onUncaughtError";
bool success = global->Get(context, tns::ToV8String(isolate, cbName)).ToLocal(&handler);
Expand Down Expand Up @@ -278,13 +290,20 @@ static void ScheduleDeferredThrow(Isolate* isolate, NSException* e) {
Log(@"NativeScript discarding uncaught JS exception!");
}

// Opt-in (default off): after reporting, crash the app with a real native
// crash report by scheduling an uncaught @throw on a scope-free frame. Skipped
// when discarding (discardUncaughtJsExceptions is an explicit "do not crash").
// uncaughtErrorPolicy — the cross-platform uncaught-error contract:
// "report" (default): report and keep the app running;
// "throw": after reporting, rethrow the unprevented error
// natively (deferred to a clean scope-free frame). This
// is a throw, not a crash guarantee — the app terminates
// only if no native handler catches it.
// The deprecated discardUncaughtJsExceptions flag suppresses the throw (an
// explicit "keep the app alive").
if (!isDiscarded) {
id crashValue = Runtime::GetAppConfigValue("crashOnUncaughtJsExceptions");
bool shouldCrash = crashValue ? [crashValue boolValue] : false;
if (shouldCrash) {
id policyValue = Runtime::GetAppConfigValue("uncaughtErrorPolicy");
std::string policy = [policyValue isKindOfClass:[NSString class]]
? std::string([(NSString*)policyValue UTF8String])
: "report";
if (policy == "throw") {
NSString* reasonText = tns::ToNSString(fullMessage);
NSDictionary* userInfo =
stackTrace.empty() ? nil : @{TNSJavaScriptStackTraceKey : tns::ToNSString(stackTrace)};
Expand All @@ -297,6 +316,12 @@ static void ScheduleDeferredThrow(Isolate* isolate, NSException* e) {
tns::SetJSStackOnException(fatal, tns::ToNSString(stackTrace));
}
ScheduleDeferredThrow(isolate, fatal);
} else if (policy != "report") {
static std::once_flag warnedPolicy;
std::call_once(warnedPolicy, [&policy]() {
Log(@"NativeScript: unknown uncaughtErrorPolicy \"%s\" — falling back to \"report\".",
policy.c_str());
});
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions TestRunner/app/tests/EscapeExceptionTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -250,9 +250,9 @@ describe("interop.escapeException and boundary hardening", function () {
});
});

// manual: crashOnUncaughtJsExceptions is not exercised automatically because a
// manual: uncaughtErrorPolicy "throw" is not exercised automatically because a
// real crash would kill the test runner. To smoke it manually, set
// { "crashOnUncaughtJsExceptions": true } in the app config and throw an
// { "uncaughtErrorPolicy": "throw" } in the app config and throw an
// unprevented error (or `throw interop.escapeException(err)` from an `error`
// listener) — the app must terminate with a NativeScriptFatalJSException
// crash report scheduled on the runtime loop. Default-off behavior (report +
Expand Down
32 changes: 19 additions & 13 deletions docs/error-handling.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Error handling

The runtime implements the WHATWG error model at the global level: uncaught JavaScript exceptions and unhandled promise rejections are dispatched as cancelable events on `globalThis`, native `NSException`s round-trip into JavaScript with the original object attached, and `interop.escapeException` forwards a JavaScript throw to a native caller as a real `@throw`. By default nothing crashes the app — reporting is opt-out per error (`preventDefault()`), and crashing is opt-in (`crashOnUncaughtJsExceptions`).
The runtime implements the WHATWG error model at the global level: uncaught JavaScript exceptions and unhandled promise rejections are dispatched as cancelable events on `globalThis`, native `NSException`s round-trip into JavaScript with the original object attached, and `interop.escapeException` forwards a JavaScript throw to a native caller as a real `@throw`. By default nothing crashes the app — reporting is opt-out per error (`preventDefault()`), and rethrowing unprevented errors natively is opt-in (`uncaughtErrorPolicy: "throw"`).

## Quick reference

Expand Down Expand Up @@ -40,7 +40,7 @@ globalThis.addEventListener("rejectionhandled", (e) => {

Notes:

- `error` and `unhandledrejection` are `cancelable`; `preventDefault()` suppresses every downstream consequence (legacy hooks, fatal log, error modal, `crashOnUncaughtJsExceptions`).
- `error` and `unhandledrejection` are `cancelable`; `preventDefault()` suppresses every downstream consequence (legacy hooks, fatal log, error modal, the `uncaughtErrorPolicy: "throw"` rethrow).
- Events fire even if app code overwrites `globalThis.dispatchEvent` — native dispatch goes through closures captured at startup.
- A listener that throws does not stop the remaining listeners; the thrown value is routed to the fatal reporting tail directly (never recursively dispatched as another `error` event).
- The events also fire on worker globals. A worker's unhandled rejection dispatches `unhandledrejection` on the worker's own global first; only when unprevented does it continue to the worker-global `onerror` and then to the main isolate's `worker.onerror`, mirroring uncaught worker errors.
Expand Down Expand Up @@ -149,27 +149,33 @@ The accessor is uniform across all cases; underneath:
|---|---|
| Synthesized escape | `userInfo[TNSJavaScriptStackTraceKey]` (`@"JavaScriptStack"`), plus `userInfo[TNSJavaScriptEscapeStackTraceKey]` (`@"JavaScriptEscapeStack"`) when the `escapeException` call site differs from the error's origin; also appended to `reason` |
| Rethrown original `NSException` | attached as an associated object (identity and `userInfo` are untouched); the string combines the origin stack and the escape site |
| `crashOnUncaughtJsExceptions` fatal (`NativeScriptFatalJSException`) | `userInfo[TNSJavaScriptStackTraceKey]`, also in `reason` |
| `uncaughtErrorPolicy: "throw"` fatal (`NativeScriptFatalJSException`) | `userInfo[TNSJavaScriptStackTraceKey]`, also in `reason` |

`tns_javascriptStackTrace` and the two `userInfo` keys are the stable contract for crash-SDK integrations.

## Configuration

Both flags live in the app's `package.json`, both default to off:
`uncaughtErrorPolicy` in the app's `package.json` is the uncaught-error contract, unified across NativeScript runtimes (9.1+):

| Flag | Effect |
|---|---|
| `discardUncaughtJsExceptions` | Unprevented errors call `__onDiscardedError` instead of `__onUncaughtError` and skip the fatal log. Also disables `crashOnUncaughtJsExceptions`. |
| `crashOnUncaughtJsExceptions` | After an unprevented error is reported, the app crashes with a real `NSException` (JS stack in `reason` and `userInfo`), thrown from a clean frame on the runtime loop so crash reporters capture it properly. |
```jsonc
{ "uncaughtErrorPolicy": "report" } // default: report and keep running
{ "uncaughtErrorPolicy": "throw" } // unprevented errors are rethrown natively
```

- `"report"` — after the event dispatch and legacy hooks, log the fatal message and keep the app alive.
- `"throw"` — additionally rethrow the error as a real `NSException` (`NativeScriptFatalJSException`, JS stack in `reason` and `userInfo`), from a clean frame on the runtime loop. This is a **throw, not a crash guarantee**: the app terminates only if no native handler catches it — which also means crash reporters capture it properly when it does.
- Unknown values log a warning once and fall back to `"report"`.

Deprecated: `discardUncaughtJsExceptions` is still honored in full for now — unprevented errors route to `__onDiscardedError` instead of `__onUncaughtError`, the fatal log is skipped, and any `"throw"` policy is suppressed — but it logs a deprecation warning. Migrate to an `error`/`unhandledrejection` listener calling `preventDefault()` (per-error, more precise) and `uncaughtErrorPolicy`.

Terminal-path decision table for an uncaught error / unhandled rejection:

| Condition | legacy hook called | fatal log / modal | native crash |
| Condition | legacy hook called | fatal log / modal | native throw |
|---|---|---|---|
| default | `__onUncaughtError` | yes | no |
| `discardUncaughtJsExceptions` | `__onDiscardedError` | no | no |
| `"report"` (default) | `__onUncaughtError` | yes | no |
| `"throw"`, unprevented | `__onUncaughtError` | yes | yes |
| listener called `preventDefault()` | no | no | no |
| `crashOnUncaughtJsExceptions`, unprevented | `__onUncaughtError` | yes | yes |
| `discardUncaughtJsExceptions` (deprecated) | `__onDiscardedError` | no | no |

## Crash reporter integration

Expand All @@ -193,7 +199,7 @@ globalThis.addEventListener("error", (e) => {
});
Comment on lines +191 to +200

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Include unhandled rejections in the crash-reporter example.

The documented reporting model includes unhandledrejection, but this sample only listens for error. Add a shared capture helper and an unhandledrejection listener, or explicitly scope the example to uncaught exceptions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/error-handling.md` around lines 191 - 200, Update the crash-reporter
example around the global error listener to also handle unhandled promise
rejections: extract the shared reporting logic into a helper, register a
globalThis unhandledrejection listener that passes the rejection reason through
it, and preserve the existing native exception metadata handling for error
events.

```

Native side — for the `NSUncaughtExceptionHandler`/signal layer, read `exception.tns_javascriptStackTrace` (or the `userInfo` keys) to attach the JS stack to crashes that never pass through the JS event layer (escaped exceptions, `crashOnUncaughtJsExceptions`).
Native side — for the `NSUncaughtExceptionHandler`/signal layer, read `exception.tns_javascriptStackTrace` (or the `userInfo` keys) to attach the JS stack to crashes that never pass through the JS event layer (escaped exceptions, `uncaughtErrorPolicy: "throw"`).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Correct the policy-throw event-path description.

uncaughtErrorPolicy: "throw" still dispatches the JS event and reporting hooks before depositing the native exception. Only the later uncaught native throw reaches NSUncaughtExceptionHandler; “never pass through the JS event layer” is accurate for escaped exceptions, not policy throws.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/error-handling.md` at line 203, Update the
NSUncaughtExceptionHandler/signal-layer description in the documentation to
distinguish escaped exceptions from uncaughtErrorPolicy: "throw": escaped
exceptions bypass the JS event layer, while policy throws dispatch JS events and
reporting hooks before the later native uncaught throw. Retain the guidance to
read exception.tns_javascriptStackTrace or userInfo keys at the native crash
boundary.


## Legacy hooks (deprecated)

Expand Down
Loading