Title: feat: web-compliant error handling by edusperoni · Pull Request #1985 · NativeScript/android · GitHub
Open Graph Title: feat: web-compliant error handling by edusperoni · Pull Request #1985 · NativeScript/android
X Title: feat: web-compliant error handling by edusperoni · Pull Request #1985 · NativeScript/android
Description: Description Ports the web-compliant error model from NativeScript/ios#409 to the Android runtime: unhandled promise rejection tracking, WHATWG error events, and interop.escapeException — with the same file layout as the iOS implementation (Events.{h,cpp} for the generic primitives, ErrorEvents.{h,cpp} for the error layer, reporting machinery and the rejection tracker in NativeScriptException). Unhandled promise rejection tracking The runtime never registered SetPromiseRejectCallback, so unhandled rejections vanished with no log, no callback, no crash. Now: Rejections without handlers are tracked per-isolate and drained once per looper turn (a LooperTasks task — the Android analogue of the iOS runloop observer), so a handler attached in the same turn always cancels the report. Unhandled ones report through the existing __onUncaughtError hook, prefixed Unhandled promise rejection: in logcat. Late-attached handlers fire rejectionhandled (as a task, per spec, carrying the original reason; already-reported promises are held weakly so GC'd ones drop out). Worker rejections dispatch unhandledrejection on the worker global first, then flow through the existing worker error channel (worker-global onerror → parent Worker.onerror). WHATWG error events on globalThis Spec-shaped Event, EventTarget, ErrorEvent, PromiseRejectionEvent constructors, addEventListener/removeEventListener/dispatchEvent on globalThis, and global reportError() — same surface as the iOS runtime, workers and Deno. Uncaught errors dispatch a cancelable error ErrorEvent; unhandled rejections a cancelable unhandledrejection PromiseRejectionEvent. preventDefault() = fully handled (no __onUncaughtError/__onDiscardedError hook, no crash): passExceptionToJsNative now returns the handled flag, and NativeScriptUncaughtExceptionHandler skips the error activity and the default (crashing) handler when it is set. Native code dispatches through closures captured at init, so events keep firing even if app code overwrites globalThis.dispatchEvent. Back-compat: unprevented errors behave exactly as before — __onUncaughtError/__onDiscardedError keep working, so current core needs zero changes. interop.escapeException New interop global (mirroring iOS) with interop.escapeException(x). The escape direction is already Android's default — a JS throw in a native-invoked override surfaces to the Java caller as a real com.tns.NativeScriptException — but a rethrown Java exception lost its identity: the boundary wrapped it, so a native catch of the concrete type never matched. Now: try { riskyJavaCall(); // throws java.io.IOException } catch (e) { throw interop.escapeException(e); } // a Java `catch (IOException e)` above the caller now catches the ORIGINAL // IOException object - not a com.tns.NativeScriptException wrapper Branded errors carrying a Java throwable are rethrown unwrapped at the boundary, preserving Throwable identity; branding is idempotent, TypeError with no arguments. Branded escapes bypass discardUncaughtJsExceptions (an explicit forward request, matching iOS where branded escapes ignore the discard flag). The JS trace rides along. A new com.tns.JavaScriptStackTrace (never thrown; API kept generic so other exception paths can adopt it) is attached to the escaped original via Throwable.addSuppressed, with the JS frames synthesized as real StackTraceElements — so the JS journey renders automatically in printStackTrace(), logcat fatal logs and crash reporters (Suppressed: com.tns.JavaScriptStackTrace: ...) while the original object's identity, class, stack and cause chain stay untouched. Idempotent across nested re-escapes. escapeException() also records its own call-site stack (previously lost; for non-Error values it's the only stack there is), exposed with the origin stack via getJavaScriptStack()/getEscapeSiteStack() for crash-SDK integrations. Synthesized escapes (branded plain JS errors) throw com.tns.NativeScriptException as before, but with its stack trace replaced by the synthesized JS frames — so crash reporters group them by where they actually happened in JS instead of bucketing everything under the identical JNI boundary machinery. Unbranded throws keep today's semantics exactly. Not needed from the iOS PR: crashOnUncaughtJsExceptions — Android already crashes by default on truly-uncaught exceptions (discardUncaughtJsExceptions and preventDefault() are the opt-outs). Containment by default + uncaughtErrorPolicy (the 9.1 model) Adopts the web's model as the default: an erroring page doesn't crash the browser, and an uncaught JS error no longer crashes the app. An uncaught throw in a native-initiated callback (the OS invoking an override, a posted Runnable, a timer, __runOnMainThread, a frame callback) is contained at the boundary: reported through the pipeline (cancelable error event → __onUncaughtError → logcat) and the native caller resumes with the return type's default value (primitives get 0/false — the dispatch layer substitutes before unboxing, fixing the NPE the old discard path produced). preventDefault() suppresses the report entirely — and since the report now happens synchronously at the boundary, it is fully meaningful on every thread. A JS-initiated chain (JS → Java → JS callback throws) keeps propagating to the outer JS catch with the original JS error object — correct JS semantics, tracked via a per-isolate JS→Java call depth. Containment applies only at an outermost native-initiated boundary. uncaughtErrorPolicy (app package.json, root): "report" (default) or "throw" — the full report (cancelable event → hook → log) runs first at the decision point (preventDefault() fully contains the error even under "throw", matching iOS), then the error is thrown to the native layer as a real Java exception with the JS frames as its stack trace, marked isReportedToJs() so the uncaught-exception path never reports the same failure twice — one event per failure on both platforms. Restores the pre-9.1 behavior (typically a crash; named for the mechanism, not a guaranteed outcome). Unhandled rejections under "throw" are thrown from a clean Java frame on the runtime's looper. error.stackTrace/reason.stackTrace are populated before the events dispatch, matching iOS's pre-dispatch fix. discardUncaughtJsExceptions is deprecated (logcat warning): true keeps its legacy quiet routing (__onDiscardedError) on top of the new default; false — which used to mean "crash" — is ignored rather than repurposed. Branded escapes are now exempt from discard handling. Migration one-liner: the new default ≡ old discardUncaughtJsExceptions: true plus the event layer; uncaughtErrorPolicy: "throw" ≡ the old default with better crash-reporter grouping. nativeuncaughterror — the native-layer death notification Native crashes get their own event, completing the invariant that error/unhandledrejection fire only while the failure is still containable (preventDefault() honest, app fully alive). Everything reaching the uncaught-exception handler un-marked — pure-native Java crashes, uncaught escapeException forwards, bootstrap failures — dispatches a cancelable nativeuncaughterror (synchronously, on the crashing thread, entering the isolate under the v8::Locker), with e.error.nativeException carrying the original Throwable. preventDefault() is best-effort (skips the error activity and the killing handler — meaningful for background threads; ignored on iOS where termination is unavoidable). Crashes on threads with no runtime of their own — previously invisible to JS entirely, since getCurrentRuntime()/isInitialized() are thread-local — now fall back to the new Runtime.getMainRuntime(). Already-reported "throw"-policy exceptions short-circuit the handler with zero work. Legacy __onUncaughtError keeps firing for unprevented native crashes (back-compat). Docs: the full model — events, escapeException, JavaScriptStackTrace, config decision table, crash-reporter integration — is documented in docs/error-handling.md, mirroring the docs on the iOS PR. Behavior changes (default config): uncaught JS errors in native-initiated callbacks no longer crash the app — they are reported and contained (set uncaughtErrorPolicy: "throw" for the old behavior); a throwing override hands its Java caller the return type's default value, so null-hostile callers may fail downstream (the real error is logged first; interop.escapeException is the out for contracts that need the exception). Unhandled rejections are now reported (previously silent). JS-initiated chains, module/script bootstrap errors, preventDefault() and escapeException semantics are as described above. ⚠️ Release coupling: this PR is 9.1-only and should merge in lockstep with the iOS counterpart (NativeScript/ios#409) so the runtimes never ship divergent defaults. Related Pull Requests NativeScript/ios#409 — the iOS implementation this ports (including its Events/ErrorEvents split) Does your pull request have unit tests? Yes — 40 new jasmine specs: testErrorEvents.js (ErrorEvent/PromiseRejectionEvent constructors, EventTarget semantics, reportError, preventDefault() suppressing the __onUncaughtError/__onDiscardedError hooks, dispatch resilience to globalThis.dispatchEvent being overwritten), testUnhandledRejections.js (reporting of Promise.reject/async throws/.then throws, same-turn .catch cancelling the report, unhandledrejection + preventDefault(), rejectionhandled for late handlers), and testEscapeException.js (brand semantics plus JS→Java boundary round-trips through a new EscapeExceptionTest fixture: the native caller catches the original java.io.IOException by identity, the suppressed JavaScriptStackTrace carrier renders frames pointing at the spec file, duplicate carriers are not stacked across nested re-escapes, synthesized escapes carry JS frames, non-Error escapes fall back to the escape-site stack, and unbranded behavior is unchanged). A new testUncaughtErrorPolicy.js suite covers containment (app liveness + event/hook with thrown-value identity), preventDefault() suppression, timer containment, the primitive-default return, and JS-initiated-chain identity; uncaughtErrorPolicy: "throw" is a documented manual smoke (a real crash would kill the runner). Full suite green on an API 35 arm64 emulator — every pre-existing suite passes unchanged under the new default thanks to the JS-initiated-chain rule. Summary by CodeRabbit New Features Added WHATWG-style global error events (error, unhandledrejection, rejectionhandled) with correct dispatch, cancellation, and listener options behavior. Added interop.escapeException for JS→Java exception escaping with preserved identity and stack context. Added uncaughtErrorPolicy app configuration ("report"/"throw"). Bug Fixes Native uncaught/promise-rejection handling now respects JavaScript preventDefault() consumption and delivers rejectionhandled reliably. Documentation Documented the global error model, interop.escapeException, and policy behavior in docs/error-handling.md. Tests Added/expanded test suites covering error-event semantics, unhandled rejections, escape behavior, and uncaught-error policy.
Open Graph Description: Description Ports the web-compliant error model from NativeScript/ios#409 to the Android runtime: unhandled promise rejection tracking, WHATWG error events, and interop.escapeException — with the s...
X Description: Description Ports the web-compliant error model from NativeScript/ios#409 to the Android runtime: unhandled promise rejection tracking, WHATWG error events, and interop.escapeException — with the s...
Opengraph URL: https://github.com/NativeScript/android/pull/1985
X: @github
Domain: github.com
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /:user_id/:repository/pull/:id/files(.:format) |
| route-controller | pull_requests |
| route-action | files |
| fetch-nonce | v2:511df9ee-dff9-5025-278f-58983c47dfcb |
| current-catalog-service-hash | ae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b |
| request-id | AE52:A71F9:E90B0A:1252203:6B01426A |
| html-safe-nonce | 6b20a2255052a1482961fe32690ee4d1436bfa3724f05e2fb2142a6fc00e1892 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBRTUyOkE3MUY5OkU5MEIwQToxMjUyMjAzOjZCMDE0MjZBIiwidmlzaXRvcl9pZCI6IjUzMDc2NTg3MDQzMDMyNDM4ODIiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 378d7d24d3bbf2876520452fcde899d1a8904818d63858b4a93de8a697765d4b |
| hovercard-subject-tag | pull_request:4119467867 |
| github-keyboard-shortcuts | repository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/NativeScript/android/pull/1985/files |
| twitter:image | https://avatars.githubusercontent.com/u/4061767?s=400&v=4 |
| twitter:card | summary_large_image |
| og:image | https://avatars.githubusercontent.com/u/4061767?s=400&v=4 |
| og:image:alt | Description Ports the web-compliant error model from NativeScript/ios#409 to the Android runtime: unhandled promise rejection tracking, WHATWG error events, and interop.escapeException — with the s... |
| og:site_name | GitHub |
| og:type | object |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| turbo-cache-control | no-preview |
| diff-view | unified |
| go-import | github.com/NativeScript/android git https://github.com/NativeScript/android.git |
| octolytics-dimension-user_id | 7392261 |
| octolytics-dimension-user_login | NativeScript |
| octolytics-dimension-repository_id | 29137950 |
| octolytics-dimension-repository_nwo | NativeScript/android |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 29137950 |
| octolytics-dimension-repository_network_root_nwo | NativeScript/android |
| turbo-body-classes | logged-out env-production page-responsive full-width |
| disable-turbo | true |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width