fix(errors): separate exception data from native failure stacks

Build script-created DOMException subclasses and deserialized exception data without attaching a new stack. Native failure factories keep V8 stack capture, including the WebTransport session-failure path that previously reused its clone builder.

Preserve inherited stack accessors, native clone fields, realm and reference identity, getter avoidance, and ordinary JS Error stacks. Reuse a fixed Chromium fixture in Window, child Window, classic Worker, and module Worker.

Validation: cargo fmt --all; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo nextest run --no-fail-fast (23213 passed, 17 existing skips, 32 threads, no retries).
This commit is contained in:
ldm0
2026-11-20 22:47:56 +08:00
parent 03eb0869e4
commit fbe28455f4
13 changed files with 88 additions and 21 deletions
+1 -1
View File
@@ -349,7 +349,7 @@ pub(crate) use self::canvas::{
};
pub(crate) use self::constructors::{
WebTransportErrorClonePayload, WebTransportErrorSource, build_dom_exception_object,
build_quota_exceeded_error_object, build_rtc_sdp_error,
build_quota_exceeded_error_object, build_rtc_sdp_error, build_web_transport_error,
build_web_transport_error_from_clone_payload, dom_exception_clone_fields,
ensure_dom_implementation_singleton, new_dom_error_value, new_dom_exception_value,
new_most_derived_dom_exception_value, new_quota_exceeded_error_value,
@@ -33,14 +33,15 @@ pub(super) use document_nodes::{
};
pub(crate) use dom_exception::{
WebTransportErrorClonePayload, WebTransportErrorSource, build_dom_exception_object,
build_overconstrained_error,
build_quota_exceeded_error_object, dom_error_constructor_callback, dom_exception_clone_fields,
dom_exception_constructor_callback, install_dom_exception_template_bindings,
new_dom_error_value, new_dom_exception_value, new_most_derived_dom_exception_value,
new_quota_exceeded_error_value, new_websocket_error_value, overconstrained_error_constructor_callback, quota_exceeded_error_clone_fields,
quota_exceeded_error_constructor_callback, rtc_error_constructor_callback,
throw_dom_exception_value, web_transport_error_clone_payload_from_object,
web_transport_error_constructor_callback, websocket_error_close_info,
build_overconstrained_error, build_quota_exceeded_error_object,
dom_error_constructor_callback, dom_exception_clone_fields, dom_exception_constructor_callback,
install_dom_exception_template_bindings, new_dom_error_value,
new_dom_exception_value, new_most_derived_dom_exception_value, new_quota_exceeded_error_value,
new_websocket_error_value, overconstrained_error_constructor_callback,
quota_exceeded_error_clone_fields, quota_exceeded_error_constructor_callback,
rtc_error_constructor_callback, throw_dom_exception_value,
web_transport_error_clone_payload_from_object, web_transport_error_constructor_callback,
websocket_error_close_info,
};
pub(crate) use dom_implementation::ensure_dom_implementation_singleton;
pub(super) use dom_implementation::install_dom_implementation_template_bindings;
@@ -69,3 +70,18 @@ pub(crate) fn build_web_transport_error_from_clone_payload<'s>(
}
dom_exception::build_web_transport_error_from_clone_payload(scope, payload)
}
pub(crate) fn build_web_transport_error<'s>(
scope: &mut v8::PinScope<'s, '_>,
payload: &WebTransportErrorClonePayload,
) -> Option<v8::Local<'s, v8::Object>> {
if !super::exposed_interfaces::is_realm_interface_exposed(scope, "WebTransportError") {
throw_dom_exception_value(
scope,
"WebTransportError is not exposed in this realm.",
"DataCloneError",
);
return None;
}
dom_exception::build_web_transport_error(scope, payload)
}
@@ -100,7 +100,7 @@ pub(super) fn fail<'s>(
.get_creation_context(scope)
.expect("WebTransport cleanup realm");
let scope = &mut v8::ContextScope::new(scope, context);
let error = super::super::build_web_transport_error_from_clone_payload(
let error = super::super::build_web_transport_error(
scope,
&super::super::WebTransportErrorClonePayload {
message: message.encode_utf16().collect(),
@@ -131,11 +131,12 @@
test('WebTransportError structured clone ' + source + ' ' + code, () => {
const e = createWT(utf16, {source, streamErrorCode:code});
const sentinel = {};
for (const name of ['name','message','source','streamErrorCode']) Object.defineProperty(e, name, {enumerable:true, get() {throw sentinel;}});
for (const name of ['name','message','source','streamErrorCode','stack']) Object.defineProperty(e, name, {enumerable:true, get() {throw sentinel;}});
const cloned = realm.structuredClone({a:e, b:e});
return cloned.a === cloned.b && cloned.a !== e && Object.getPrototypeOf(cloned.a) === realm.WebTransportError.prototype &&
cloned.a.name === 'WebTransportError' && cloned.a.message === utf16 && cloned.a.source === source &&
cloned.a.streamErrorCode === code && cloned.a.code === 0 && !Object.hasOwn(cloned.a, 'name');
cloned.a.streamErrorCode === code && cloned.a.code === 0 && !Object.hasOwn(cloned.a, 'name') &&
!Object.hasOwn(cloned.a, 'stack') && typeof cloned.a.stack === 'undefined';
});
}
test('WebTransportError author Proxy clone rejects without traps', () => {
@@ -24,7 +24,7 @@ fn native_exception_stacks_ignore_mutated_javascript_capture_helpers() {
assert_eq!(actual[realm]["failures"], serde_json::json!([]), "{actual}");
assert_eq!(
actual[realm]["rows"].as_array().unwrap().len(),
29,
37,
"{actual}"
);
}
@@ -0,0 +1,30 @@
use super::*;
#[tokio::test]
async fn worker_dom_exception_data_and_native_failures_have_distinct_stack_boundaries() {
ensure_v8();
for kind in [WorkerScriptKind::Classic, WorkerScriptKind::Module] {
let source = format!(
"{}\npostMessage(domExceptionStackBoundariesProbe(globalThis)); close();",
include_str!("../../../../tests/fixtures/dom-exception-stack-boundaries.js"),
);
let mut handle = spawn_worker_with_request_client_and_kind(
source,
"https://worker-error-stack.test/worker.js".to_owned(),
worker_test_request_client(),
kind,
);
let actual: serde_json::Value =
serde_json::from_str(&recv_post_json(&mut handle).await).unwrap();
assert_eq!(
actual["failures"],
serde_json::json!([]),
"{kind:?}: {actual}"
);
assert_eq!(
actual["rows"].as_array().unwrap().len(),
28,
"{kind:?}: {actual}"
);
}
}
@@ -1,5 +1,6 @@
mod callback_execution;
mod console;
mod dom_exception_stacks;
mod error_reporting_guard;
mod geometry_matrix_constructor_union;
#[cfg(feature = "devtools")]
@@ -8,8 +8,9 @@ function domExceptionStackBoundariesProbe(realm) {
['DOMException', ['message', 'AbortError']],
['QuotaExceededError', ['full', {quota: 10, requested: 12}]],
['WebSocketError', ['closed']],
['WebTransportError', []],
];
if (realm.document) entries.push(['RTCError', [{errorDetail: 'dtls-failure'}, 'rtc']]);
if (realm.document) entries.push(['RTCError', [{errorDetail: 'dtls-failure'}, 'rtc']], ['OverconstrainedError', ['width', 'constraint']]);
const descriptor = Object.getOwnPropertyDescriptor(realm.Error, 'captureStackTrace');
let captureReads = 0;
Object.defineProperty(realm.Error, 'captureStackTrace', {configurable: true, get() {captureReads++; throw new Error('author capture lookup');}});
+5 -1
View File
@@ -296,6 +296,10 @@
wt.close({closeCode: 33, reason: 'bye'});
const e = await rejected(wt.closed);
assert(e instanceof WebTransportError && e.source === 'session' && e.streamErrorCode === null);
assert(Object.hasOwn(e, 'stack') && typeof e.stack === 'string');
const copy = structuredClone(e);
assert(copy instanceof WebTransportError && copy.source === 'session' && copy.streamErrorCode === null);
assert(!Object.hasOwn(copy, 'stack') && typeof copy.stack === 'undefined');
assert(await rejected(wt.ready) === e && await rejected(read) === e);
throws(() => wt.createSendGroup(), 'InvalidStateError');
});
@@ -384,7 +388,7 @@
assert(await rejected(wt.ready) instanceof WebTransportError);
});
await check('dedicated workers own failure tasks and stream promises', async () => {
const source = `onmessage=async()=>{try{const wt=new WebTransport('https://web-platform.localhost:0/',{datagramsReadableType:'bytes'});const reader=wt.datagrams.readable.getReader({mode:'byob'});const read=reader.read(new Uint8Array(16)).catch(e=>e);const stats=wt.getStats().catch(e=>e);let before=true;wt.ready.catch(()=>{before=false});await Promise.resolve();const pending=before;const e=await wt.ready.catch(e=>e);const closed=await wt.closed.catch(e=>e);const result=await stats;postMessage({ok:pending&&e instanceof WebTransportError&&e===closed&&await read===e&&result.name==='InvalidStateError'&&wt.reliability==='pending'});}catch(e){postMessage({ok:false,error:String(e.stack||e)})}};`;
const source = `onmessage=async()=>{try{const wt=new WebTransport('https://web-platform.localhost:0/',{datagramsReadableType:'bytes'});const reader=wt.datagrams.readable.getReader({mode:'byob'});const read=reader.read(new Uint8Array(16)).catch(e=>e);const stats=wt.getStats().catch(e=>e);let before=true;wt.ready.catch(()=>{before=false});await Promise.resolve();const pending=before;const e=await wt.ready.catch(e=>e);const closed=await wt.closed.catch(e=>e);const result=await stats;postMessage({ok:pending&&e instanceof WebTransportError&&Object.hasOwn(e,'stack')&&typeof e.stack==='string'&&e===closed&&await read===e&&result.name==='InvalidStateError'&&wt.reliability==='pending'});}catch(e){postMessage({ok:false,error:String(e.stack||e)})}};`;
const url = URL.createObjectURL(new Blob([source], {type: 'text/javascript'}));
const worker = new Worker(url);
try {
+7 -2
View File
@@ -10,10 +10,13 @@ use webidl::WebIdlDictionarySerialize;
mod overconstrained_error;
mod rtc_error;
mod web_transport_error;
pub use overconstrained_error::{build_overconstrained_error, overconstrained_error_constructor_callback};
pub use overconstrained_error::{
build_overconstrained_error, overconstrained_error_constructor_callback,
};
pub use rtc_error::{build_rtc_sdp_error, rtc_error_constructor_callback};
pub use web_transport_error::{
WebTransportErrorClonePayload, WebTransportErrorSource,
WebTransportErrorClonePayload, WebTransportErrorSource, build_web_transport_error,
build_web_transport_error_from_clone_payload, web_transport_error_clone_payload_from_object,
web_transport_error_constructor_callback,
};
@@ -529,7 +532,9 @@ fn websocket_error_declaration<'s>(
WebSocketErrorObjectDeclaration::new(message, close_code, reason)
}
/// Create exception data without inventing a construction or deserialization stack.
pub fn build_dom_exception_object<'s>(
scope: &mut v8::PinScope<'s, '_>,
message: &str,
name: &str,
@@ -64,7 +64,6 @@ pub fn overconstrained_error_constructor_callback<'s>(
.initialize(scope, args.this())
.is_ok()
{
capture_dom_exception_stack(scope, args.this());
rv.set(args.this().into());
}
}
@@ -91,7 +91,6 @@ pub fn web_transport_error_constructor_callback<'s>(
return;
};
if declaration.initialize(scope, args.this()).is_ok() {
capture_dom_exception_stack(scope, args.this());
rv.set(args.this().into());
}
}
@@ -161,7 +160,14 @@ pub fn build_web_transport_error_from_clone_payload<'s>(
payload: &WebTransportErrorClonePayload,
) -> Option<v8::Local<'s, v8::Object>> {
global_constructor_prototype(scope, "WebTransportError")?;
let object = declaration(scope, payload)?.bind(scope).ok()?;
declaration(scope, payload)?.bind(scope).ok()
}
pub fn build_web_transport_error<'s>(
scope: &mut v8::PinScope<'s, '_>,
payload: &WebTransportErrorClonePayload,
) -> Option<v8::Local<'s, v8::Object>> {
let object = build_web_transport_error_from_clone_payload(scope, payload)?;
capture_dom_exception_stack(scope, object);
Some(object)
}
+5 -1
View File
@@ -438,7 +438,11 @@ fn native_error_and_transport_clone_builders_use_destination_intrinsics_after_gl
assert!(dom_exception::dom_exception_clone_fields(scope, native).is_some());
let not_an_error = v8_string(scope, "not a native error").unwrap();
assert!(dom_exception::websocket_error_close_info(scope, not_an_error.into()).is_none());
assert!(eval(scope, "Object.hasOwn(transportClone, 'stack')").is_true());
assert!(eval(scope, "!Object.hasOwn(transportClone, 'stack')").is_true());
assert!(eval(scope, "Object.hasOwn(nativeError, 'stack')").is_true());
let failure = dom_exception::build_web_transport_error(scope, &payload).unwrap();
publish(scope, "transportFailure", failure);
assert!(eval(scope, "transportFailure instanceof nativeTransport && Object.hasOwn(transportFailure, 'stack')").is_true());
}
#[test]