Skip to content

Commit

Permalink
LibWeb: Add formatters for WebIDL exception types
Browse files Browse the repository at this point in the history
This adds formatters for `WebIDL::Exception`, `WebIDL::SimpleException`
and `WebIDL::DomException`. These are useful for displaying the content
of errors when debugging
  • Loading branch information
tcl3 committed Jan 22, 2025
1 parent 3050768 commit 63f88b1
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Libraries/LibWeb/WebIDL/DOMException.h
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,15 @@ inline JS::Completion throw_completion(GC::Ref<WebIDL::DOMException> exception)
}

}

namespace AK {

template<>
struct Formatter<Web::WebIDL::DOMException> : Formatter<FormatString> {
ErrorOr<void> format(FormatBuilder& builder, Web::WebIDL::DOMException const& exception)
{
return Formatter<FormatString>::format(builder, "{}: {}"sv, exception.name(), exception.message());
}
};

}
50 changes: 50 additions & 0 deletions Libraries/LibWeb/WebIDL/ExceptionOr.h
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,53 @@ class [[nodiscard]] ExceptionOr<void> : public ExceptionOr<Empty> {
};

}

namespace AK {

template<>
struct Formatter<Web::WebIDL::SimpleException> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, Web::WebIDL::SimpleException const& exception)
{
auto message_view = exception.message.visit(
[](String const& message) -> StringView {
return message.bytes_as_string_view();
},
[](StringView message) -> StringView {
return message;
});

return Formatter<StringView>::format(builder, message_view);
}
};

template<>
struct Formatter<Web::WebIDL::Exception> : Formatter<FormatString> {
ErrorOr<void> format(FormatBuilder& builder, Web::WebIDL::Exception const& exception)
{
return exception.visit(
[&](Web::WebIDL::SimpleException const& simple_exception) -> ErrorOr<void> {
return Formatter<FormatString>::format(builder, "{}"sv, simple_exception);
},
[&](GC::Ref<Web::WebIDL::DOMException> const& dom_exception) -> ErrorOr<void> {
return Formatter<FormatString>::format(builder, "{}"sv, *dom_exception);
},
[&](JS::Completion const& completion) -> ErrorOr<void> {
VERIFY(completion.is_error());
auto value = *completion.value();

if (value.is_object()) {
auto& object = value.as_object();
static const JS::PropertyKey message_property_key { "message" };
auto has_message_or_error = object.has_own_property(message_property_key);
if (!has_message_or_error.is_error() && has_message_or_error.value()) {
auto message_object = object.get_without_side_effects(message_property_key);
return Formatter<StringView>::format(builder, message_object.to_string_without_side_effects());
}
}

return Formatter<StringView>::format(builder, value.to_string_without_side_effects());
});
}
};

}

0 comments on commit 63f88b1

Please sign in to comment.