Handle exceptions from JSON::stringify

This commit is contained in:
Andrew Chin 2018-08-10 14:10:51 -04:00
parent 23cb0ea656
commit f5203bba8a
3 changed files with 30 additions and 4 deletions

View File

@ -2683,8 +2683,8 @@ extern "C" {
/// specified. /// specified.
/// ///
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
#[wasm_bindgen(static_method_of = JSON)] #[wasm_bindgen(catch, static_method_of = JSON)]
pub fn stringify(obj: &JsValue) -> JsString; pub fn stringify(obj: &JsValue) -> Result<JsString, JsValue>;
} }

View File

@ -0,0 +1,4 @@
exports.set_in_object = function(obj, name, value) {
obj[name] = value;
};

View File

@ -1,8 +1,15 @@
use wasm_bindgen::JsValue; use wasm_bindgen::JsValue;
use wasm_bindgen_test::*; use wasm_bindgen_test::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast; use wasm_bindgen::JsCast;
use js_sys::*; use js_sys::*;
#[wasm_bindgen(module = "tests/wasm/JSON.js")]
extern {
fn set_in_object(obj: &Object, name: &str, value: &JsValue);
}
#[wasm_bindgen_test] #[wasm_bindgen_test]
fn parse_array() { fn parse_array() {
@ -63,7 +70,22 @@ fn stringify() {
arr.push(&JsValue::from(true)); arr.push(&JsValue::from(true));
arr.push(&JsValue::from("hello")); 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); let rust_str: String = From::from(str);
assert_eq!(rust_str, "[1,true,\"hello\"]"); assert_eq!(rust_str, "[1,true,\"hello\"]");
} }
#[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::<Error>());
let err: &Error = err_obj.dyn_ref().unwrap();
let err_msg: String = From::from(err.message());
assert!(err_msg.contains("rust really rocks"));
}