js-sys: Catch exceptions thrown in Reflect APIs

Proxies passed to Reflect APIs can throw for any of these operations and it is a
bit of a mess.
This commit is contained in:
Nick Fitzgerald
2018-09-25 11:55:28 -07:00
parent 6edb871c36
commit e3d2ea2628
10 changed files with 171 additions and 92 deletions

View File

@ -1,9 +1,9 @@
extern crate wasm_bindgen;
extern crate js_sys;
extern crate wasm_bindgen;
use js_sys::{Function, Object, Reflect, Uint8Array, WebAssembly};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use js_sys::{WebAssembly, Object, Reflect, Function, Uint8Array};
// lifted from the `console_log` example
#[wasm_bindgen]
@ -30,22 +30,21 @@ pub fn run() -> Result<(), JsValue> {
// (aka do a memory allocation in Rust) it'll cause the buffer to change.
// That means we can't actually do any memory allocations after we do this
// until we pass it back to JS.
let my_memory = Uint8Array::new(&my_memory.buffer())
.subarray(
WASM.as_ptr() as u32,
WASM.as_ptr() as u32 + WASM.len() as u32,
);
let my_memory = Uint8Array::new(&my_memory.buffer()).subarray(
WASM.as_ptr() as u32,
WASM.as_ptr() as u32 + WASM.len() as u32,
);
let a = WebAssembly::Module::new(my_memory.as_ref())?;
let b = WebAssembly::Instance::new(&a, &Object::new())?;
let c = b.exports();
let add = Reflect::get(c.as_ref(), &"add".into())
let add = Reflect::get(c.as_ref(), &"add".into())?
.dyn_into::<Function>()
.expect("add export wasn't a function");
let three = add.call2(&JsValue::undefined(), &1.into(), &2.into())?;
console_log!("1 + 2 = {:?}", three);
let mem = Reflect::get(c.as_ref(), &"memory".into())
let mem = Reflect::get(c.as_ref(), &"memory".into())?
.dyn_into::<WebAssembly::Memory>()
.expect("memory export wasn't a `WebAssembly.Memory`");
console_log!("created module has {} pages of memory", mem.grow(0));