ExceptionReporter.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. dbgln("{}", error_value.stack_string(JS::CompactTraceback::Yes));
  31. console.report_exception(error_value, error_in_promise == ErrorInPromise::Yes);
  32. return;
  33. }
  34. } else {
  35. dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", value);
  36. }
  37. console.report_exception(*JS::Error::create(realm, value.to_string_without_side_effects()), error_in_promise == ErrorInPromise::Yes);
  38. }
  39. // https://html.spec.whatwg.org/#report-the-exception
  40. void report_exception(JS::Completion const& throw_completion, JS::Realm& realm)
  41. {
  42. VERIFY(throw_completion.type() == JS::Completion::Type::Throw);
  43. VERIFY(throw_completion.value().has_value());
  44. report_exception_to_console(*throw_completion.value(), realm, ErrorInPromise::No);
  45. }
  46. }