ExceptionReporter.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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/Console.h>
  8. #include <LibJS/Runtime/ConsoleObject.h>
  9. #include <LibJS/Runtime/VM.h>
  10. #include <LibJS/Runtime/Value.h>
  11. #include <LibWeb/Bindings/MainThreadVM.h>
  12. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  13. namespace Web::HTML {
  14. void report_exception_to_console(JS::Value value, JS::Realm& realm, ErrorInPromise error_in_promise)
  15. {
  16. auto& console = realm.intrinsics().console_object()->console();
  17. if (value.is_object()) {
  18. auto& object = value.as_object();
  19. auto& vm = object.vm();
  20. auto name = object.get_without_side_effects(vm.names.name).value_or(JS::js_undefined());
  21. auto message = object.get_without_side_effects(vm.names.message).value_or(JS::js_undefined());
  22. if (name.is_accessor() || message.is_accessor()) {
  23. // The result is not going to be useful, let's just print the value. This affects DOMExceptions, for example.
  24. dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", JS::Value(&object));
  25. } else {
  26. dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m [{}] {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", name, message);
  27. }
  28. if (is<JS::Error>(object)) {
  29. auto const& error_value = static_cast<JS::Error const&>(object);
  30. for (auto& traceback_frame : error_value.traceback()) {
  31. auto& function_name = traceback_frame.function_name;
  32. auto& source_range = traceback_frame.source_range();
  33. dbgln(" {} at {}:{}:{}", function_name, source_range.filename(), source_range.start.line, source_range.start.column);
  34. }
  35. console.report_exception(error_value, error_in_promise == ErrorInPromise::Yes);
  36. return;
  37. }
  38. } else {
  39. dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", value);
  40. }
  41. console.report_exception(*JS::Error::create(realm, value.to_string_without_side_effects()), error_in_promise == ErrorInPromise::Yes);
  42. }
  43. // https://html.spec.whatwg.org/#report-the-exception
  44. void report_exception(JS::Completion const& throw_completion, JS::Realm& realm)
  45. {
  46. VERIFY(throw_completion.type() == JS::Completion::Type::Throw);
  47. VERIFY(throw_completion.value().has_value());
  48. report_exception_to_console(*throw_completion.value(), realm, ErrorInPromise::No);
  49. }
  50. }