diff --git a/crates/js-sys/src/lib.rs b/crates/js-sys/src/lib.rs index caaf9cda..282c77d6 100644 --- a/crates/js-sys/src/lib.rs +++ b/crates/js-sys/src/lib.rs @@ -2683,8 +2683,8 @@ extern "C" { /// specified. /// /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify - #[wasm_bindgen(static_method_of = JSON)] - pub fn stringify(obj: &JsValue) -> JsString; + #[wasm_bindgen(catch, static_method_of = JSON)] + pub fn stringify(obj: &JsValue) -> Result; } diff --git a/crates/js-sys/tests/wasm/JSON.js b/crates/js-sys/tests/wasm/JSON.js new file mode 100644 index 00000000..796bd200 --- /dev/null +++ b/crates/js-sys/tests/wasm/JSON.js @@ -0,0 +1,4 @@ +exports.set_in_object = function(obj, name, value) { + obj[name] = value; +}; + diff --git a/crates/js-sys/tests/wasm/JSON.rs b/crates/js-sys/tests/wasm/JSON.rs index 70ece6e8..c7f0f4bb 100644 --- a/crates/js-sys/tests/wasm/JSON.rs +++ b/crates/js-sys/tests/wasm/JSON.rs @@ -1,8 +1,15 @@ use wasm_bindgen::JsValue; use wasm_bindgen_test::*; +use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use js_sys::*; + +#[wasm_bindgen(module = "tests/wasm/JSON.js")] +extern { + fn set_in_object(obj: &Object, name: &str, value: &JsValue); +} + #[wasm_bindgen_test] fn parse_array() { @@ -63,7 +70,22 @@ fn stringify() { arr.push(&JsValue::from(true)); arr.push(&JsValue::from("hello")); - let str = JSON::stringify(&JsValue::from(arr)); + let str = JSON::stringify(&JsValue::from(arr)).unwrap(); let rust_str: String = From::from(str); assert_eq!(rust_str, "[1,true,\"hello\"]"); -} \ No newline at end of file +} + +#[wasm_bindgen_test] +fn stringify_error() { + let func = Function::new_no_args("throw new Error(\"rust really rocks\")"); + let obj = Object::new(); + set_in_object(&obj, "toJSON", &JsValue::from(func)); + + let result = JSON::stringify(&JsValue::from(obj)); + assert!(result.is_err()); + let err_obj = result.unwrap_err(); + assert!(err_obj.is_instance_of::()); + let err: &Error = err_obj.dyn_ref().unwrap(); + let err_msg: String = From::from(err.message()); + assert!(err_msg.contains("rust really rocks")); +}