ExceptionReporter.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. void print_error_from_value(JS::Value value, ErrorInPromise error_in_promise)
  12. {
  13. // FIXME: We should probably also report these exceptions to the JS console.
  14. if (value.is_object()) {
  15. auto& object = value.as_object();
  16. auto& vm = object.vm();
  17. auto name = object.get_without_side_effects(vm.names.name).value_or(JS::js_undefined());
  18. auto message = object.get_without_side_effects(vm.names.message).value_or(JS::js_undefined());
  19. if (name.is_accessor() || message.is_accessor()) {
  20. // The result is not going to be useful, let's just print the value. This affects DOMExceptions, for example.
  21. dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", JS::Value(&object));
  22. } else {
  23. dbgln("\033[31;1mUnhandled JavaScript exception{}:\033[0m [{}] {}", error_in_promise == ErrorInPromise::Yes ? " (in promise)" : "", name, message);
  24. }
  25. if (is<JS::Error>(object)) {
  26. auto const& error_value = static_cast<JS::Error const&>(object);
  27. for (auto const& traceback_frame : error_value.traceback()) {
  28. auto const& function_name = traceback_frame.function_name;
  29. auto const& source_range = traceback_frame.source_range;
  30. dbgln(" {} at {}:{}:{}", function_name, source_range.filename, source_range.start.line, source_range.start.column);
  31. }
  32. }
  33. } else {
  34. dbgln("\033[31;1mUnhandled JavaScript exception:\033[0m {}", value);
  35. }
  36. }
  37. // https://html.spec.whatwg.org/#report-the-exception
  38. void report_exception(JS::Completion const& throw_completion)
  39. {
  40. // FIXME: This is just old code, and does not strictly follow the spec of report an exception.
  41. VERIFY(throw_completion.type() == JS::Completion::Type::Throw);
  42. VERIFY(throw_completion.value().has_value());
  43. print_error_from_value(*throw_completion.value(), ErrorInPromise::No);
  44. }
  45. }