ExceptionReporter.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * Copyright (c) 2022, David Tuin <davidot@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/TypeCasts.h>
  7. #include <LibJS/Runtime/VM.h>
  8. #include <LibJS/Runtime/Value.h>
  9. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  10. namespace Web::HTML {
  11. // https://html.spec.whatwg.org/#report-the-exception
  12. void report_exception(JS::ThrowCompletionOr<JS::Value> const& result)
  13. {
  14. // FIXME: This is just old code, and does not strictly follow the spec of report an exception.
  15. // FIXME: We should probably also report these exceptions to the JS console.
  16. VERIFY(result.throw_completion().value().has_value());
  17. auto thrown_value = *result.throw_completion().value();
  18. if (thrown_value.is_object()) {
  19. auto& object = thrown_value.as_object();
  20. auto& vm = object.vm();
  21. auto name = object.get_without_side_effects(vm.names.name).value_or(JS::js_undefined());
  22. auto message = object.get_without_side_effects(vm.names.message).value_or(JS::js_undefined());
  23. if (name.is_accessor() || message.is_accessor()) {
  24. // The result is not going to be useful, let's just print the value. This affects DOMExceptions, for example.
  25. dbgln("\033[31;1mUnhandled JavaScript exception:\033[0m {}", thrown_value);
  26. } else {
  27. dbgln("\033[31;1mUnhandled JavaScript exception:\033[0m [{}] {}", name, message);
  28. }
  29. if (is<JS::Error>(object)) {
  30. auto const& error_value = static_cast<JS::Error const&>(object);
  31. for (auto const& traceback_frame : error_value.traceback()) {
  32. auto const& function_name = traceback_frame.function_name;
  33. auto const& source_range = traceback_frame.source_range;
  34. dbgln(" {} at {}:{}:{}", function_name, source_range.filename, source_range.start.line, source_range.start.column);
  35. }
  36. }
  37. } else {
  38. dbgln("\033[31;1mUnhandled JavaScript exception:\033[0m {}", thrown_value);
  39. }
  40. }
  41. }