1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use crate::{
    exec::Interpreter,
    js::{
        function::NativeFunctionData,
        object::{ObjectKind, PROTOTYPE},
        value::{to_value, ResultValue, Value, ValueData},
    },
};
use gc::Gc;

/// Create a new error
pub fn make_error(this: &Value, args: &[Value], _: &Interpreter) -> ResultValue {
    if !args.is_empty() {
        this.set_field_slice("message", to_value(args.get(0).unwrap().to_string()));
    }
    // This value is used by console.log and other routines to match Object type
    // to its Javascript Identifier (global constructor method name)
    this.set_kind(ObjectKind::Error);
    Ok(Gc::new(ValueData::Undefined))
}
/// Get the string representation of the error
pub fn to_string(this: &Value, _: &[Value], _: &Interpreter) -> ResultValue {
    let name = this.get_field_slice("name");
    let message = this.get_field_slice("message");
    Ok(to_value(format!("{}: {}", name, message).to_string()))
}
/// Create a new `Error` object
pub fn _create(global: &Value) -> Value {
    let prototype = ValueData::new_obj(Some(global));
    prototype.set_field_slice("message", to_value(""));
    prototype.set_field_slice("name", to_value("Error"));
    prototype.set_field_slice("toString", to_value(to_string as NativeFunctionData));
    let error = to_value(make_error as NativeFunctionData);
    error.set_field_slice(PROTOTYPE, prototype);
    error
}
/// Initialise the global object with the `Error` object
pub fn init(global: &Value) {
    global.set_field_slice("Error", _create(global));
}