Skip to content

Truly independent web browser

LibWeb: Report the information of worker errors to the outside global

Andreas Kling95aa8ba944d3
diff --git a/Libraries/LibJS/Console.cpp b/Libraries/LibJS/Console.cpp
index b6ae158c9d3..95a2e05fa74 100644
--- a/Libraries/LibJS/Console.cpp
+++ b/Libraries/LibJS/Console.cpp
@@ -213,6 +213,11 @@ void Console::report_exception(Utf16View name, Utf16View message, ErrorData cons
js_console_report_exception(console_to_abi(*this), utf16_view_to_abi(name), utf16_view_to_abi(message), error_data_to_abi(error_data), in_promise);
}
+void Console::report_exception(Utf16View name, Utf16View message, Utf16View filename, u32 line, u32 column, bool in_promise) const
+{
+ js_console_report_exception_with_location(console_to_abi(*this), utf16_view_to_abi(name), utf16_view_to_abi(message), utf16_view_to_abi(filename), line, column, in_promise);
+}
+
static GC::Ref<EngineConsoleClient> create_engine_console_client(Console& console, ConsoleClient& client)
{
auto* engine_console_client = js_console_client_create(vm_to_abi(console.vm()), console_to_abi(console), &ConsoleClientMethodThunks::methods, static_cast<GC::Cell*>(&client));
diff --git a/Libraries/LibJS/Console.h b/Libraries/LibJS/Console.h
index ab37ea9cbf2..048d146e3cb 100644
--- a/Libraries/LibJS/Console.h
+++ b/Libraries/LibJS/Console.h
@@ -62,6 +62,7 @@ public:
void output_debug_message(LogLevel log_level, StringView output) const;
void output_debug_message(LogLevel log_level, Utf16View output) const;
void report_exception(Utf16View name, Utf16View message, JS::ErrorData const&, bool) const;
+ void report_exception(Utf16View name, Utf16View message, Utf16View filename, u32 line, u32 column, bool in_promise) const;
};
// The cell of the Rust runtime that a console holds as its client. It forwards what the console logs to the virtual
diff --git a/Libraries/LibJS/Rust/src/embedding/console.rs b/Libraries/LibJS/Rust/src/embedding/console.rs
index dcf5a9a1609..6339b517661 100644
--- a/Libraries/LibJS/Rust/src/embedding/console.rs
+++ b/Libraries/LibJS/Rust/src/embedding/console.rs
@@ -20,7 +20,10 @@ use crate::layout::cell::Gc;
use crate::layout::host_class::{JSObject, JSVM, JSValue};
use crate::layout::value::Value;
use crate::runtime::console_object::ConsoleObject;
+use crate::runtime::error_data::ErrorData;
use crate::runtime::print::{PrintContext, print};
+use crate::source_code::SourceCode;
+use crate::source_range::{Position, SourceRange};
/// The Console of a realm's console object, which keeps its counters, timers and group stack and hands what it logs
/// to its client.
@@ -174,6 +177,32 @@ pub unsafe extern "C" fn js_console_report_exception(
console.report_exception(name, message, error_data, in_promise);
}
+/// Reports an exception whose source location came from another agent. The location becomes its console stack frame.
+///
+/// # Safety
+///
+/// `console` must point to a live console, and the views must be valid for the call. Call on the VM's thread.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn js_console_report_exception_with_location(
+ console: *mut JSConsole,
+ name: JSUtf16View,
+ message: JSUtf16View,
+ filename: JSUtf16View,
+ line: u32,
+ column: u32,
+ in_promise: bool,
+) {
+ // SAFETY: The caller passes a live console.
+ let console = unsafe { console_from_abi(console) };
+ // SAFETY: The caller guarantees that the views are valid for the call.
+ let (name, message, filename) = unsafe { (name.as_view(), message.as_view(), filename.as_view()) };
+ let error_data = ErrorData::from_source_range(SourceRange {
+ code: SourceCode::create(filename.to_utf16_string(), ak::Utf16String::default()),
+ start: Position { line, column },
+ });
+ console.report_exception(name, message, &error_data, in_promise);
+}
+
/// The stream a PrintContext writes to, which hands the bytes to the embedder's sink.
struct ByteSinkWriter<'a> {
sink: &'a JSByteSink,
diff --git a/Libraries/LibJS/Rust/src/runtime/error_data.rs b/Libraries/LibJS/Rust/src/runtime/error_data.rs
index 98b486a4333..4c95d720eea 100644
--- a/Libraries/LibJS/Rust/src/runtime/error_data.rs
+++ b/Libraries/LibJS/Rust/src/runtime/error_data.rs
@@ -85,6 +85,17 @@ impl ErrorData {
}
}
+ /// Error data for an exception whose source location came from another agent.
+ pub fn from_source_range(source_range: SourceRange) -> Self {
+ Self {
+ traceback: vec![TracebackFrame {
+ function_name: Utf16String::default(),
+ cached_source_range: Some(source_range),
+ }],
+ cached_string: Cell::new(None),
+ }
+ }
+
pub fn traceback_storage_size(&self) -> usize {
self.traceback.capacity() * size_of::<TracebackFrame>()
}
diff --git a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp
index 8f57044dc58..57b0f65434d 100644
--- a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp
@@ -68,6 +68,11 @@ void report_exception_to_console(JS::Value value, JS::Realm& realm, ErrorInPromi
// https://html.spec.whatwg.org/multipage/webappapis.html#report-an-exception
void report_an_exception(JS::Object& global, JS::Value exception, OmitError omit_error, GC::Ptr<Script> script)
+{
+ report_an_exception(global, exception, {}, omit_error, script);
+}
+
+void report_an_exception(JS::Object& global, JS::Value exception, Optional<ErrorInformation> precomputed_error_info, OmitError omit_error, GC::Ptr<Script> script)
{
auto& realm = relevant_realm(global);
auto& vm = realm.vm();
@@ -76,7 +81,10 @@ void report_an_exception(JS::Object& global, JS::Value exception, OmitError omit
bool not_handled = true;
// 2. Let errorInfo be the result of extracting error information from exception.
- auto error_info = extract_error_information(vm, exception);
+ // NB: An exception from a dedicated worker stays in the worker, so its Worker object's relevant global object
+ // reports it with the information the worker sent along with it.
+ bool has_precomputed_error_info = precomputed_error_info.has_value();
+ auto error_info = has_precomputed_error_info ? precomputed_error_info.release_value() : extract_error_information(vm, exception);
// 3. Let script be a script found in an implementation-defined way, or null. This should usually be the
// running script (most notably during run a classic script).
@@ -159,7 +167,11 @@ void report_an_exception(JS::Object& global, JS::Value exception, OmitError omit
}
}
// 3. Otherwise, the user agent may report exception to a developer console.
- else {
+ else if (has_precomputed_error_info) {
+ dbgln("\033[31;1mUnhandled JavaScript exception:\033[0m {}", error_info.message);
+ dbgln(" at {}:{}:{}", error_info.filename, error_info.lineno, error_info.colno);
+ realm.intrinsics().console_object()->console().report_exception("Error"_utf16, error_info.message, error_info.filename, error_info.lineno, error_info.colno, false);
+ } else {
report_exception_to_console(exception, realm, ErrorInPromise::No);
}
}
diff --git a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.h b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.h
index 4c5e477b95b..5a5c3128b8a 100644
--- a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.h
+++ b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.h
@@ -6,9 +6,11 @@
#pragma once
+#include <AK/Optional.h>
#include <LibGC/Ptr.h>
#include <LibJS/Forward.h>
#include <LibWeb/Export.h>
+#include <LibWeb/HTML/ErrorInformation.h>
namespace Web::HTML {
@@ -27,6 +29,7 @@ enum class OmitError {
void report_exception_to_console(JS::Value, JS::Realm&, ErrorInPromise);
WEB_API void report_exception(JS::Completion const&, JS::Realm&);
void report_an_exception(JS::Object& global, JS::Value exception, OmitError = OmitError::No, GC::Ptr<Script> = {});
+void report_an_exception(JS::Object& global, JS::Value exception, Optional<ErrorInformation>, OmitError = OmitError::No, GC::Ptr<Script> = {});
template<typename T>
inline void report_exception(JS::ThrowCompletionOr<T> const& result, JS::Realm& realm)
diff --git a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp b/Libraries/LibWeb/HTML/WorkerAgentParent.cpp
index ed5c0a13bcc..47c7fcdd6c2 100644
--- a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp
+++ b/Libraries/LibWeb/HTML/WorkerAgentParent.cpp
@@ -43,7 +43,14 @@ static void report_worker_exception(WindowOrWorkerGlobalScopeMixin& window_or_wo
{
auto& realm = relevant_realm(window_or_worker);
auto wrapped_error = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { error });
- report_an_exception(relevant_global_object(window_or_worker), wrapped_error, OmitError::Yes);
+ ErrorInformation error_info {
+ .message = error.message(),
+ .filename = error.filename(),
+ .error = wrapped_error,
+ .lineno = error.lineno(),
+ .colno = error.colno(),
+ };
+ report_an_exception(relevant_global_object(window_or_worker), wrapped_error, move(error_info), OmitError::Yes);
}
GC::Ref<WorkerAgentParent> WorkerAgentParent::create(URL::URL url, WorkerOptions const& options,
diff --git a/Tests/LibWeb/Text/expected/wpt-import/workers/constructors/Worker/AbstractWorker.onerror.txt b/Tests/LibWeb/Text/expected/wpt-import/workers/constructors/Worker/AbstractWorker.onerror.txt
index 1039a686230..36e2073279a 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/workers/constructors/Worker/AbstractWorker.onerror.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/workers/constructors/Worker/AbstractWorker.onerror.txt
@@ -2,5 +2,5 @@ Harness status: OK
Found 1 tests
-1 Fail
-Fail AbstractWorker.onerror
\ No newline at end of file
+1 Pass
+Pass AbstractWorker.onerror
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/workers/interfaces/WorkerGlobalScope/onerror/propagate-to-window-onerror.txt b/Tests/LibWeb/Text/expected/wpt-import/workers/interfaces/WorkerGlobalScope/onerror/propagate-to-window-onerror.txt
index fd163e5d9f6..e92f7e3734b 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/workers/interfaces/WorkerGlobalScope/onerror/propagate-to-window-onerror.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/workers/interfaces/WorkerGlobalScope/onerror/propagate-to-window-onerror.txt
@@ -2,5 +2,5 @@ Harness status: OK
Found 1 tests
-1 Fail
-Fail onerror, "not handled" with only window.onerror defined
\ No newline at end of file
+1 Pass
+Pass onerror, "not handled" with only window.onerror defined
\ No newline at end of file
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index 4df37e664fe..a7b6f7dc7fd 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -324,6 +324,11 @@ if (BUILD_TESTING AND NOT WIN32)
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-devtools-catch-up-layout.py $<TARGET_FILE:ladybird>
)
set_tests_properties(TestDevToolsCatchUpLayout PROPERTIES TIMEOUT 120)
+ add_test(
+ NAME TestWorkerErrorConsole
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-worker-error-console.py $<TARGET_FILE:ladybird>
+ )
+ set_tests_properties(TestWorkerErrorConsole PROPERTIES TIMEOUT 120)
add_test(
NAME TestWindowSizeReachesEveryPage
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-window-size-reaches-every-page.py $<TARGET_FILE:ladybird>
diff --git a/Tests/LibWebView/test-worker-error-console.py b/Tests/LibWebView/test-worker-error-console.py
new file mode 100755
index 00000000000..8863d957db7
--- /dev/null
+++ b/Tests/LibWebView/test-worker-error-console.py
@@ -0,0 +1,91 @@
+#!/usr/bin/env python3
+#
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+import argparse
+import http.server
+import json
+import runpy
+import tempfile
+import threading
+
+from pathlib import Path
+
+devtools = runpy.run_path(str(Path(__file__).with_name("test-devtools-client-follows-the-tab.py")))
+PAGE = b"""<!doctype html><title>worker-console</title>
+<script>
+window.onerror = (message, filename, line, column) => {
+ window.lastError = { message, filename, line, column };
+};
+</script>
+"""
+WORKER = b'\nthrow new Error("worker console sentinel");\n'
+
+
+class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ if self.path == "/favicon.ico":
+ self.send_error(404)
+ return
+ self.send_response(200)
+ self.send_header("Content-Type", "text/javascript" if self.path == "/worker.js" else "text/html")
+ self.end_headers()
+ self.wfile.write(WORKER if self.path == "/worker.js" else PAGE)
+
+ def log_message(self, format, *args):
+ pass
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("ladybird_binary")
+ ladybird_binary = parser.parse_args().ladybird_binary
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ origin = f"http://127.0.0.1:{server.server_port}"
+ url = origin + "/page"
+ worker_url = origin + "/worker.js"
+ try:
+ with tempfile.TemporaryDirectory(prefix="ladybird-worker-console-") as profile:
+ process, _, client = devtools["launch"](ladybird_binary, profile, url)
+ try:
+ devtools["wait_for_page"](client, url, "worker-console")
+ client.watch_frame_targets()
+ errors = []
+ receive = client.receive
+
+ def receive_and_record_errors():
+ packet = receive()
+ if packet.get("type") == "resources-available-array":
+ for resource_type, resources in packet.get("array", []):
+ if resource_type == "error-message":
+ errors.extend(resource["pageError"] for resource in resources)
+ return packet
+
+ # Keep error resources even if they arrive while evaluation is retried after a target change.
+ client.receive = receive_and_record_errors
+ client.evaluate("window.worker = new Worker('/worker.js'); undefined")
+ if not errors:
+ client.receive_matching(lambda packet: bool(errors))
+ preview = errors[0]["exception"]["preview"]
+ event = json.loads(client.evaluate("JSON.stringify(window.lastError)"))
+ assert "worker console sentinel" in event["message"], event
+ assert preview["message"] == event["message"], preview
+ assert event["filename"] == worker_url, event
+ assert event["line"] == 2 and event["column"] > 0, event
+ expected_location = f"@{worker_url}:{event['line']}:{event['column']}\n"
+ assert preview.get("stack") == expected_location, preview
+ assert not errors[0]["isPromiseRejection"], errors[0]
+ print("PASS: An unhandled worker exception keeps its message and source location in the console")
+ finally:
+ client.close()
+ devtools["stop"](process)
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+if __name__ == "__main__":
+ main()