mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2025-04-22 12:35:14 +00:00
LibJS: Implement Error.prototype.toString()
This commit is contained in:
parent
2636cac6e4
commit
94afcb54de
Notes:
sideshowbarker
2024-07-19 07:58:59 +09:00
Author: https://github.com/linusg Commit: https://github.com/SerenityOS/serenity/commit/94afcb54de0 Pull-request: https://github.com/SerenityOS/serenity/pull/1590
3 changed files with 39 additions and 0 deletions
|
@ -38,6 +38,7 @@ ErrorPrototype::ErrorPrototype()
|
|||
{
|
||||
put_native_property("name", name_getter, nullptr);
|
||||
put_native_property("message", message_getter, nullptr);
|
||||
put_native_function("toString", to_string);
|
||||
}
|
||||
|
||||
ErrorPrototype::~ErrorPrototype()
|
||||
|
@ -64,4 +65,27 @@ Value ErrorPrototype::message_getter(Interpreter& interpreter)
|
|||
return js_string(interpreter.heap(), static_cast<const Error*>(this_object)->message());
|
||||
}
|
||||
|
||||
Value ErrorPrototype::to_string(Interpreter& interpreter)
|
||||
{
|
||||
if (!interpreter.this_value().is_object())
|
||||
return interpreter.throw_exception<Error>("TypeError", "Not an object");
|
||||
auto& this_object = interpreter.this_value().as_object();
|
||||
|
||||
String name = "Error";
|
||||
auto object_name_property = this_object.get("name");
|
||||
if (object_name_property.has_value() && !object_name_property.value().is_undefined())
|
||||
name = object_name_property.value().to_string();
|
||||
|
||||
String message = "";
|
||||
auto object_message_property = this_object.get("message");
|
||||
if (object_message_property.has_value() && !object_message_property.value().is_undefined())
|
||||
message = object_message_property.value().to_string();
|
||||
|
||||
if (name.length() == 0)
|
||||
return js_string(interpreter.heap(), message);
|
||||
if (message.length() == 0)
|
||||
return js_string(interpreter.heap(), name);
|
||||
return js_string(interpreter.heap(), String::format("%s: %s", name.characters(), message.characters()));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -38,6 +38,8 @@ public:
|
|||
private:
|
||||
virtual const char* class_name() const override { return "ErrorPrototype"; }
|
||||
|
||||
static Value to_string(Interpreter&);
|
||||
|
||||
static Value name_getter(Interpreter&);
|
||||
static Value message_getter(Interpreter&);
|
||||
};
|
||||
|
|
13
Libraries/LibJS/Tests/Error.prototype.toString.js
Normal file
13
Libraries/LibJS/Tests/Error.prototype.toString.js
Normal file
|
@ -0,0 +1,13 @@
|
|||
function assert(x) { if (!x) throw 1; }
|
||||
|
||||
try {
|
||||
assert(Error().toString() === "Error");
|
||||
assert(Error(undefined).toString() === "Error");
|
||||
assert(Error(null).toString() === "Error: null");
|
||||
assert(Error("test").toString() === "Error: test");
|
||||
assert(Error(42).toString() === "Error: 42");
|
||||
|
||||
console.log("PASS");
|
||||
} catch (e) {
|
||||
console.log("FAIL: " + e);
|
||||
}
|
Loading…
Add table
Reference in a new issue