소스 검색

LibJS: Throw error in Object::to_string() if string conversion fails

Linus Groh 5 년 전
부모
커밋
2c6e7dbd07
2개의 변경된 파일14개의 추가작업 그리고 3개의 파일을 삭제
  1. 7 1
      Libraries/LibJS/Runtime/Object.cpp
  2. 7 2
      Libraries/LibJS/Runtime/Value.cpp

+ 7 - 1
Libraries/LibJS/Runtime/Object.cpp

@@ -360,7 +360,13 @@ Value Object::to_string() const
         && to_string_property.is_object()
         && to_string_property.is_object()
         && to_string_property.as_object().is_function()) {
         && to_string_property.as_object().is_function()) {
         auto& to_string_function = static_cast<Function&>(to_string_property.as_object());
         auto& to_string_function = static_cast<Function&>(to_string_property.as_object());
-        return const_cast<Object*>(this)->interpreter().call(to_string_function, const_cast<Object*>(this));
+        auto& interpreter = const_cast<Object*>(this)->interpreter();
+        auto string_value = interpreter.call(to_string_function, const_cast<Object*>(this));
+        if (!string_value.is_string())
+            interpreter.throw_exception<TypeError>("Cannot convert object to string");
+        if (interpreter.exception())
+            return {};
+        return string_value;
     }
     }
     return js_string(heap(), String::format("[object %s]", class_name()));
     return js_string(heap(), String::format("[object %s]", class_name()));
 }
 }

+ 7 - 2
Libraries/LibJS/Runtime/Value.cpp

@@ -69,8 +69,13 @@ String Value::to_string() const
         return String::format("%.4f", as_double());
         return String::format("%.4f", as_double());
     }
     }
 
 
-    if (is_object())
-        return as_object().to_primitive(Object::PreferredType::String).to_string();
+    if (is_object()) {
+        auto primitive_value = as_object().to_primitive(Object::PreferredType::String);
+        // FIXME: Maybe we should pass in the Interpreter& and call interpreter.exception() instead?
+        if (primitive_value.is_empty())
+            return {};
+        return primitive_value.to_string();
+    }
 
 
     if (is_string())
     if (is_string())
         return m_value.as_string->string();
         return m_value.as_string->string();