Skip to content

Lightpanda: the headless browser designed for AI and automation

cdp: emit Runtime.exceptionThrown for unhandled promise rejections

Lucien Coffe32b2c2cd979f
diff --git a/src/Notification.zig b/src/Notification.zig
index 634fb2863..a32a0c7a7 100644
--- a/src/Notification.zig
+++ b/src/Notification.zig
@@ -388,12 +388,15 @@ pub const ConsoleMessage = struct {
};
// An uncaught exception reported to a window and not cancelled by an "error"
-// listener: what Chrome logs as "Uncaught …" and sends as
+// listener, or a promise rejection still unhandled at the end of a microtask
+// checkpoint and not cancelled by an "unhandledrejection" listener: what
+// Chrome logs as "Uncaught …" or "Uncaught (in promise) …" and sends as
// Runtime.exceptionThrown.
pub const ExceptionThrown = struct {
timestamp: u64,
value: js.Value,
location: js.Value.ErrorLocation,
+ kind: enum { exception, rejection } = .exception,
};
pub fn init(allocator: Allocator) !*Notification {
diff --git a/src/browser/js/Context.zig b/src/browser/js/Context.zig
index 8e8e93ae0..31b84dd95 100644
--- a/src/browser/js/Context.zig
+++ b/src/browser/js/Context.zig
@@ -125,12 +125,27 @@ script_manager: *ScriptManagerBase,
// Our macrotasks
scheduler: Scheduler,
+// Promises rejected without a handler since the last microtask checkpoint. A
+// handler attached before the checkpoint ends withdraws the promise: it was
+// never unhandled. What is left is reported by Env.runMicrotasks.
+rejected_promises: std.ArrayList(RejectedPromise) = .empty,
+
// Execution context for worker-compatible APIs. This provides a common
// interface that works in both Page and Worker contexts.
execution: Execution,
unknown_properties: (if (lp.IS_DEBUG) std.StringHashMapUnmanaged(UnknownPropertyStat) else void) = if (lp.IS_DEBUG) .{} else {},
+pub const RejectedPromise = struct {
+ promise: js.Promise.Global,
+ reason: js.Value.Global,
+
+ pub fn release(self: RejectedPromise) void {
+ self.promise.release();
+ self.reason.release();
+ }
+};
+
const ModuleEntry = struct {
// Can be null if we're asynchronously loading the module, in
// which case resolver_promise cannot be null.
@@ -202,6 +217,11 @@ pub fn deinit(self: *Context) void {
// this can release objects
self.scheduler.deinit();
+ for (self.rejected_promises.items) |rejected| {
+ rejected.release();
+ }
+ self.rejected_promises.deinit(env.allocator);
+
for (self.global_modules.items) |*global| {
v8.v8__Global__Reset(global);
}
@@ -408,6 +428,19 @@ fn evaluateModule(self: *Context, comptime want_result: bool, mod: js.Module, ur
// Some module-loading errors aren't handled by TryCatch. We need to
// get the error from the module itself.
const exception = mod.getException();
+
+ // A module script that throws while it evaluates rejects its
+ // evaluation promise rather than throwing. That promise is ours, not
+ // the page's: like a classic script's, the exception is reported as
+ // uncaught, not as an unhandled rejection.
+ if (comptime want_result == false) {
+ if (self.withdrawRejectedReason(exception)) {
+ self.global.reportError(exception) catch |report_err| {
+ log.debug(.js, "report module error", .{ .specifier = url, .err = report_err });
+ };
+ }
+ }
+
const message = blk: {
const e = exception.toString() catch break :blk "???";
break :blk e.toSlice() catch "???";
@@ -1196,6 +1229,51 @@ fn enqueueMicrotask(self: *Context, callback: anytype) void {
}.run, self);
}
+// A promise rejected with no handler. It is reported at the end of the
+// microtask checkpoint if it still has none.
+pub fn addRejectedPromise(self: *Context, promise: js.Promise, reason: js.Value) !void {
+ const promise_global = try promise.persist();
+ errdefer promise_global.release();
+ const reason_global = try reason.persist();
+ errdefer reason_global.release();
+
+ try self.rejected_promises.append(self.env.allocator, .{
+ .promise = promise_global,
+ .reason = reason_global,
+ });
+}
+
+// A handler was attached to `promise`. False when it wasn't waiting to be
+// reported (it was already reported, or rejected in another context).
+pub fn withdrawRejectedPromise(self: *Context, promise: js.Promise) bool {
+ for (self.rejected_promises.items, 0..) |rejected, i| {
+ if (rejected.promise.isEqual(promise)) {
+ rejected.release();
+ _ = self.rejected_promises.orderedRemove(i);
+ return true;
+ }
+ }
+ return false;
+}
+
+// Drops the rejections waiting with `reason`, for a caller that reports it
+// itself. True when there was one.
+fn withdrawRejectedReason(self: *Context, reason: js.Value) bool {
+ var found = false;
+ var i: usize = 0;
+ while (i < self.rejected_promises.items.len) {
+ const rejected = self.rejected_promises.items[i];
+ if (rejected.reason.isEqual(reason)) {
+ rejected.release();
+ _ = self.rejected_promises.orderedRemove(i);
+ found = true;
+ } else {
+ i += 1;
+ }
+ }
+ return found;
+}
+
// There's an assumption here: the js.Function will be alive when microtasks are
// run. If we're Env.runMicrotasks in all the places that we're supposed to, then
// this should be safe (I think). In whatever HandleScope a microtask is enqueued,
diff --git a/src/browser/js/Env.zig b/src/browser/js/Env.zig
index cafe8ef70..ca721cfcc 100644
--- a/src/browser/js/Env.zig
+++ b/src/browser/js/Env.zig
@@ -505,22 +505,104 @@ pub fn runMicrotasks(self: *Env) void {
var i: usize = 0;
while (i < self.contexts.items.len) : (i += 1) {
const ctx = self.contexts.items[i];
- const page_scope = ctx.page.logScope();
- v8.v8__MicrotaskQueue__PerformCheckpoint(ctx.microtask_queue, v8_isolate);
- page_scope.exit();
-
- if (self.terminatePending()) {
- if (v8.v8__Isolate__IsExecutionTerminating(v8_isolate)) {
- // No context is entered (checked above), so it's safe to
- // clear the termination flag.
- v8.v8__Isolate__CancelTerminateExecution(v8_isolate);
+ // Reporting a rejection runs the page's listeners, which can queue
+ // microtasks: checkpoint again, a bounded number of times.
+ var rounds: u8 = 0;
+ while (true) : (rounds += 1) {
+ const page_scope = ctx.page.logScope();
+ v8.v8__MicrotaskQueue__PerformCheckpoint(ctx.microtask_queue, v8_isolate);
+ const reported = !self.terminatePending() and rounds < max_rejection_rounds and self.reportRejectedPromises(ctx);
+ page_scope.exit();
+
+ if (self.terminatePending()) {
+ if (v8.v8__Isolate__IsExecutionTerminating(v8_isolate)) {
+ // No context is entered (checked above), so it's safe to
+ // clear the termination flag.
+ v8.v8__Isolate__CancelTerminateExecution(v8_isolate);
+ }
+ return;
+ }
+ if (!reported) {
+ break;
}
- return;
}
}
}
}
+// Bounds the checkpoints a chain of unhandled rejections can trigger in a row.
+// What is left waits for the next checkpoint.
+const max_rejection_rounds = 16;
+
+// HTML's "notify about rejected promises", at the end of the microtask
+// checkpoint: a promise still rejected without a handler is unhandled. The
+// global gets "unhandledrejection" and, unless that is cancelled, the
+// rejection is reported as uncaught. Returns whether there was any, in which
+// case page code may have run and queued microtasks, and the context is still
+// alive.
+fn reportRejectedPromises(self: *Env, ctx: *Context) bool {
+ if (ctx.rejected_promises.items.len == 0) {
+ return false;
+ }
+
+ var batch = ctx.rejected_promises;
+ ctx.rejected_promises = .empty;
+ defer batch.deinit(self.allocator);
+ defer for (batch.items) |rejected| rejected.release();
+
+ for (batch.items) |rejected| {
+ if (self.terminatePending()) {
+ break;
+ }
+ // A listener removed the frame this context belonged to.
+ if (std.mem.findScalar(*Context, self.contexts.items, ctx) == null) {
+ return false;
+ }
+
+ var ls: js.Local.Scope = undefined;
+ ctx.localScope(&ls);
+ defer ls.deinit();
+
+ reportRejectedPromise(ctx, rejected.promise.local(&ls.local), rejected.reason.local(&ls.local));
+ }
+ return true;
+}
+
+fn reportRejectedPromise(ctx: *Context, promise: js.Promise, reason: js.Value) void {
+ // Reporting calls back into Zig (the listeners, the reason's toString). At
+ // call_depth 0 that resets the call_arena, which holds the location.
+ const call_depth = ctx.call_depth;
+ ctx.call_depth = call_depth + 1;
+ defer ctx.call_depth = call_depth;
+
+ ctx.page.recordJsError(error.JsException);
+ ctx.page.status.noteException(reason.toStringSlice() catch "");
+
+ const canceled = switch (ctx.global) {
+ .frame => |frame| frame.window.unhandledPromiseRejection(true, promise, reason, frame),
+ .worker => |wsg| wsg.unhandledPromiseRejection(true, promise, reason),
+ } catch |err| {
+ log.debug(.browser, "unhandled rejection handler", .{ .err = err, .target = if (ctx.global == .frame) "window" else "worker" });
+ return;
+ };
+ if (canceled) {
+ return;
+ }
+
+ const location = reason.errorLocation(ctx.call_arena) catch js.Value.ErrorLocation{};
+ log.warn(.page_error, "unhandled rejection", .{
+ .reason = reason.toStringSlice() catch "Unknown reason",
+ .url = location.url,
+ .line = location.line,
+ .column = location.column,
+ });
+ switch (ctx.global) {
+ .frame => |frame| Window.notifyExceptionThrown(reason, location, .rejection, frame),
+ // As with a worker's reportError, logged only.
+ .worker => {},
+ }
+}
+
pub fn runMacrotasks(self: *Env) !void {
if (self.terminatePending()) {
return;
@@ -835,47 +917,41 @@ fn promiseRejectCallback(message_handle: v8.PromiseRejectMessage) callconv(.c) v
ctx.call_depth += 1;
defer ctx.call_depth -= 1;
- const no_handler = promise_event == v8.kPromiseRejectWithNoHandler;
- if (no_handler and log.enabled(.page_error, .debug)) {
- // debug because it can still get a handler later, so it might get handled
- logUnhandledRejection(&local, v8.v8__PromiseRejectMessage__GetValue(&message_handle));
+ const rejection: js.PromiseRejection = .{ .local = &local, .handle = &message_handle };
+ const promise = rejection.promise();
+
+ if (promise_event == v8.kPromiseRejectWithNoHandler) {
+ // Not unhandled yet: a handler can still come before the end of the
+ // microtask checkpoint (see reportRejectedPromises).
+ const reason = rejection.reason() orelse return;
+ ctx.addRejectedPromise(promise, reason) catch |err| {
+ log.debug(.browser, "queue rejected promise", .{ .err = err });
+ };
+ return;
+ }
+
+ // A handler came for a rejection still waiting to be reported: it was
+ // never unhandled, and the page hears of neither.
+ for (ctx.env.contexts.items) |c| {
+ if (c.withdrawRejectedPromise(promise)) {
+ return;
+ }
}
switch (ctx.global) {
.frame => |frame| {
- frame.window.unhandledPromiseRejection(no_handler, .{
- .local = &local,
- .handle = &message_handle,
- }, frame) catch |err| {
+ _ = frame.window.unhandledPromiseRejection(false, promise, rejection.reason(), frame) catch |err| {
log.debug(.browser, "unhandled rejection handler", .{ .err = err, .target = "window" });
};
},
.worker => |wsg| {
- wsg.unhandledPromiseRejection(no_handler, .{
- .local = &local,
- .handle = &message_handle,
- }) catch |err| {
+ _ = wsg.unhandledPromiseRejection(false, promise, rejection.reason()) catch |err| {
log.debug(.browser, "unhandled rejection handler", .{ .err = err, .target = "worker" });
};
},
}
}
-fn logUnhandledRejection(local: *const js.Local, reason_handle: ?*const v8.Value) void {
- const handle = reason_handle orelse {
- log.debug(.page_error, "unhandled rejection", .{ .reason = "undefined" });
- return;
- };
- const reason = js.Value{ .local = local, .handle = handle };
- const location = reason.errorLocation(local.call_arena) catch js.Value.ErrorLocation{};
- log.debug(.page_error, "unhandled rejection", .{
- .reason = reason.toStringSlice() catch "Unknown reason",
- .url = location.url,
- .line = location.line,
- .column = location.column,
- });
-}
-
// V8 reports an exception that escapes to the top without a TryCatch. We
// *should* have a TryCatch at every Zig-initiated call, so this is almost
// certainly from a queueMicrotask callback. report it.
diff --git a/src/browser/js/Promise.zig b/src/browser/js/Promise.zig
index 64b49428d..03d628123 100644
--- a/src/browser/js/Promise.zig
+++ b/src/browser/js/Promise.zig
@@ -90,4 +90,8 @@ pub const Global = struct {
.handle = @ptrCast(v8.v8__Global__Get(&self.slot.handle, l.isolate.handle)),
};
}
+
+ pub fn isEqual(self: Global, other: Promise) bool {
+ return v8.v8__Global__IsEqual(&self.slot.handle, @ptrCast(other.handle));
+ }
};
diff --git a/src/browser/tests/page/module_throw.html b/src/browser/tests/page/module_throw.html
new file mode 100644
index 000000000..2c79e568c
--- /dev/null
+++ b/src/browser/tests/page/module_throw.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<script src="../testing.js"></script>
+
+<script>
+ // A module script that throws while it evaluates is reported like a classic
+ // script's exception: an "error" event, not an "unhandledrejection".
+ const reported = [];
+ window.addEventListener('error', (e) => {
+ reported.push('error:' + e.error.message);
+ e.preventDefault();
+ });
+ window.addEventListener('unhandledrejection', (e) => {
+ reported.push('unhandledrejection:' + e.reason.message);
+ e.preventDefault();
+ });
+</script>
+
+<script type=module>
+ throw new Error('module-throw');
+</script>
+
+<script id=module_throw>
+ testing.onload(() => testing.expectEqual(['error:module-throw'], reported));
+</script>
diff --git a/src/browser/webapi/Window.zig b/src/browser/webapi/Window.zig
index d0b3f8e34..7407d8d24 100644
--- a/src/browser/webapi/Window.zig
+++ b/src/browser/webapi/Window.zig
@@ -514,7 +514,7 @@ pub fn reportError(self: *Window, err: js.Value, frame: *Frame) !void {
.line = location.line,
.column = location.column,
});
- notifyExceptionThrown(err, location, frame);
+ notifyExceptionThrown(err, location, .exception, frame);
return;
}
@@ -548,17 +548,19 @@ pub fn reportError(self: *Window, err: js.Value, frame: *Frame) !void {
.line = error_event._line_number,
.column = error_event._column_number,
});
- notifyExceptionThrown(err, location, frame);
+ notifyExceptionThrown(err, location, .exception, frame);
}
}
-// An error event left uncancelled leaves the exception "uncaught": CDP
-// clients learn about it through Runtime.exceptionThrown.
-fn notifyExceptionThrown(err: js.Value, location: js.Value.ErrorLocation, frame: *Frame) void {
+// An error event (or unhandledrejection event) left uncancelled leaves the
+// exception "uncaught": CDP clients learn about it through
+// Runtime.exceptionThrown.
+pub fn notifyExceptionThrown(err: js.Value, location: js.Value.ErrorLocation, kind: @FieldType(Notification.ExceptionThrown, "kind"), frame: *Frame) void {
frame._session.notification.dispatch(.exception_thrown, &.{
.timestamp = lp.datetime.timestamp(.boot),
.value = err,
.location = location,
+ .kind = kind,
});
}
@@ -904,24 +906,29 @@ fn getWebDriver(_: *const Window) @import("WebDriver.zig") {
return .{};
}
-pub fn unhandledPromiseRejection(self: *Window, no_handler: bool, rejection: js.PromiseRejection, frame: *Frame) !void {
+// "unhandledrejection" for a promise still rejected without a handler at the
+// end of a microtask checkpoint, "rejectionhandled" for one that got a handler
+// after that. Env.reportRejectedPromises reports an "unhandledrejection" the
+// page doesn't cancel. Returns whether the event was cancelled.
+pub fn unhandledPromiseRejection(self: *Window, no_handler: bool, promise: js.Promise, reason: ?js.Value, frame: *Frame) !bool {
const event_name = if (no_handler) "unhandledrejection" else "rejectionhandled";
- if (no_handler) {
- frame.page.recordJsError(error.JsException);
- if (rejection.reason()) |reason| {
- frame.page.status.noteException(reason.toStringSlice() catch "");
- }
- }
-
const target = self.asEventTarget();
- if (frame._event_manager.hasDirectListeners(target, event_name)) {
- const event = (try @import("event/PromiseRejectionEvent.zig").init(event_name, .{
- .reason = if (rejection.reason()) |r| try r.persist() else null,
- .promise = try rejection.promise().persist(),
- }, frame.page)).asEvent();
- try frame._event_manager.dispatchDirect(target, event, .{ .context = "window.unhandledrejection" });
+ if (!frame._event_manager.hasDirectListeners(target, event_name)) {
+ return false;
}
+
+ const event = (try @import("event/PromiseRejectionEvent.zig").init(event_name, .{
+ .reason = if (reason) |r| try r.persist() else null,
+ .promise = try promise.persist(),
+ .cancelable = no_handler,
+ }, frame.page)).asEvent();
+ // Keep the event alive past dispatch so we can read _prevent_default.
+ event.acquireRef();
+ defer event.releaseRef(frame.page);
+
+ try frame._event_manager.dispatchDirect(target, event, .{ .context = "window.unhandledrejection" });
+ return event._prevent_default;
}
// Some properties are readonly but [Replaceable]. They get assigned as own
diff --git a/src/browser/webapi/WorkerGlobalScope.zig b/src/browser/webapi/WorkerGlobalScope.zig
index 2aa3a5da9..f0633f2c7 100644
--- a/src/browser/webapi/WorkerGlobalScope.zig
+++ b/src/browser/webapi/WorkerGlobalScope.zig
@@ -334,24 +334,26 @@ pub fn structuredClone(_: *const WorkerGlobalScope, value: JS.Value) !JS.Value {
return value.structuredClone();
}
-pub fn unhandledPromiseRejection(self: *WorkerGlobalScope, no_handler: bool, rejection: JS.PromiseRejection) !void {
+// See Window.unhandledPromiseRejection.
+pub fn unhandledPromiseRejection(self: *WorkerGlobalScope, no_handler: bool, promise: JS.Promise, reason: ?JS.Value) !bool {
const event_name = if (no_handler) "unhandledrejection" else "rejectionhandled";
- if (no_handler) {
- self.page.recordJsError(error.JsException);
- if (rejection.reason()) |reason| {
- self.page.status.noteException(reason.toStringSlice() catch "");
- }
- }
-
const target = self.asEventTarget();
- if (self._event_manager.hasDirectListeners(target, event_name)) {
- const event = (try @import("event/PromiseRejectionEvent.zig").init(event_name, .{
- .reason = if (rejection.reason()) |r| try r.persist() else null,
- .promise = try rejection.promise().persist(),
- }, self.page)).asEvent();
- try self.dispatch(target, event, .{});
+ if (!self._event_manager.hasDirectListeners(target, event_name)) {
+ return false;
}
+
+ const event = (try @import("event/PromiseRejectionEvent.zig").init(event_name, .{
+ .reason = if (reason) |r| try r.persist() else null,
+ .promise = try promise.persist(),
+ .cancelable = no_handler,
+ }, self.page)).asEvent();
+ // Keep the event alive past dispatch so we can read _prevent_default.
+ event.acquireRef();
+ defer event.releaseRef(self.page);
+
+ try self.dispatch(target, event, .{});
+ return event._prevent_default;
}
fn importScripts(self: *WorkerGlobalScope, urls: []const [:0]const u8) !void {
diff --git a/src/browser/webapi/streams/ReadableStreamDefaultController.zig b/src/browser/webapi/streams/ReadableStreamDefaultController.zig
index 8453063b0..eb2a6e1ed 100644
--- a/src/browser/webapi/streams/ReadableStreamDefaultController.zig
+++ b/src/browser/webapi/streams/ReadableStreamDefaultController.zig
@@ -316,7 +316,8 @@ test "ReadableStreamDefaultController: chunks and pending reads release their gl
\\}
\\{
\\ let c;
- \\ new ReadableStream({ start(ctrl) { c = ctrl; } }).getReader().read();
+ \\ // handled, so the rejection isn't held until a microtask checkpoint
+ \\ new ReadableStream({ start(ctrl) { c = ctrl; } }).getReader().read().catch(() => {});
\\ c.error('boom');
\\}
\\{
diff --git a/src/server/cdp/domains/runtime.zig b/src/server/cdp/domains/runtime.zig
index 6ce4090ef..219503a59 100644
--- a/src/server/cdp/domains/runtime.zig
+++ b/src/server/cdp/domains/runtime.zig
@@ -210,7 +210,10 @@ pub fn exceptionThrown(arena: Allocator, bc: *CDP.BrowserContext, event: *const
.timestamp = event.timestamp,
.exceptionDetails = ExceptionDetails{
.exceptionId = exception_id,
- .text = "Uncaught",
+ .text = switch (event.kind) {
+ .exception => "Uncaught",
+ .rejection => "Uncaught (in promise)",
+ },
.lineNumber = location.line -| 1,
.columnNumber = location.column -| 1,
.url = if (location.url.len == 0) null else location.url,
@@ -388,6 +391,104 @@ test "cdp.runtime: an exception whose error event is cancelled is not reported"
try testing.expectEqual(1, try countSentEvents(&ctx, "Runtime.exceptionThrown", "SID-X"));
}
+test "cdp.runtime: an unhandled rejection emits Runtime.exceptionThrown once" {
+ testing.expectLog(&.{.page_error});
+
+ var ctx = try testing.context();
+ defer ctx.deinit();
+
+ var bc = try ctx.loadBrowserContext(.{ .id = "BID-REJ1", .url = "hi.html", .target_id = "FID-000000REJ1".* });
+ try ctx.processMessage(.{ .id = 70, .method = "Runtime.enable" });
+
+ const frame = bc.mainFrame() orelse unreachable;
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+ _ = try ls.local.exec(
+ \\window.unhandled = 0;
+ \\window.addEventListener('unhandledrejection', () => window.unhandled += 1);
+ \\Promise.reject(new TypeError('nope'));
+ , null);
+ // Reported at the end of the microtask checkpoint, not when rejected.
+ try testing.expectEqual(0, try countSentEvents(&ctx, "Runtime.exceptionThrown", "SID-X"));
+ ls.local.runMicrotasks();
+
+ try ctx.expectSentEvent("Runtime.exceptionThrown", .{
+ .exceptionDetails = .{
+ .text = "Uncaught (in promise)",
+ .exception = .{ .type = "object", .subtype = "error", .className = "TypeError" },
+ .executionContextId = bc.inspector().getContextId(&ls.local),
+ },
+ }, .{});
+
+ // A later checkpoint doesn't report it again.
+ ls.local.runMicrotasks();
+ try testing.expectEqual(1, try countSentEvents(&ctx, "Runtime.exceptionThrown", "SID-X"));
+ try testing.expectEqual(1, try (try ls.local.exec("window.unhandled", null)).toI32());
+}
+
+test "cdp.runtime: a rejection handled before the checkpoint ends is not reported" {
+ var ctx = try testing.context();
+ defer ctx.deinit();
+
+ var bc = try ctx.loadBrowserContext(.{ .id = "BID-REJ2", .url = "hi.html", .target_id = "FID-000000REJ2".* });
+ try ctx.processMessage(.{ .id = 71, .method = "Runtime.enable" });
+
+ const frame = bc.mainFrame() orelse unreachable;
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+ // V8 sees each promise rejected with no handler, then gets one: in the
+ // same script, from a microtask, and on an async function's promise.
+ _ = try ls.local.exec(
+ \\window.events = [];
+ \\window.addEventListener('unhandledrejection', (e) => window.events.push(e.type));
+ \\window.addEventListener('rejectionhandled', (e) => window.events.push(e.type));
+ \\Promise.reject(new Error('now')).catch(() => {});
+ \\const later = Promise.reject(new Error('later'));
+ \\Promise.resolve().then(() => later.catch(() => {}));
+ \\async function f() { throw new Error('async'); }
+ \\f().catch(() => {});
+ , null);
+ ls.local.runMicrotasks();
+
+ try testing.expectEqual(0, try countSentEvents(&ctx, "Runtime.exceptionThrown", "SID-X"));
+ try testing.expectEqual(0, try (try ls.local.exec("window.events.length", null)).toI32());
+}
+
+test "cdp.runtime: a rejection whose unhandledrejection event is cancelled is not reported" {
+ testing.expectLog(&.{.page_error});
+
+ var ctx = try testing.context();
+ defer ctx.deinit();
+
+ var bc = try ctx.loadBrowserContext(.{ .id = "BID-REJ3", .url = "hi.html", .target_id = "FID-000000REJ3".* });
+ try ctx.processMessage(.{ .id = 72, .method = "Runtime.enable" });
+
+ const frame = bc.mainFrame() orelse unreachable;
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+ // preventDefault() on unhandledrejection marks the rejection handled, as
+ // in Chrome; only the second one is uncaught.
+ _ = try ls.local.exec(
+ \\const quiet = (e) => e.preventDefault();
+ \\window.addEventListener('unhandledrejection', quiet);
+ \\Promise.reject('quiet');
+ , null);
+ ls.local.runMicrotasks();
+ _ = try ls.local.exec(
+ \\window.removeEventListener('unhandledrejection', quiet);
+ \\Promise.reject('loud');
+ , null);
+ ls.local.runMicrotasks();
+
+ try ctx.expectSentEvent("Runtime.exceptionThrown", .{
+ .exceptionDetails = .{ .text = "Uncaught (in promise)", .exception = .{ .type = "string", .value = "loud" } },
+ }, .{});
+ try testing.expectEqual(1, try countSentEvents(&ctx, "Runtime.exceptionThrown", "SID-X"));
+}
+
test "cdp.runtime: consoleAPICalled type matches the console method" {
testing.silenceLog(&.{.js});