catch

catch 屬性允許捕捉 JavaScript 異常。這可以附加到任何導入的函式或方法,並且函式必須返回 Result,其中 Err 的酬載是 JsValue


# #![allow(unused_variables)]
#fn main() {
#[wasm_bindgen]
extern "C" {
    // `catch` on a standalone function.
    #[wasm_bindgen(catch)]
    fn foo() -> Result<(), JsValue>;

    // `catch` on a method.
    type Zoidberg;
    #[wasm_bindgen(catch, method)]
    fn woop_woop_woop(this: &Zoidberg) -> Result<u32, JsValue>;
}
#}

如果調用導入的函式拋出異常,則將返回 Err,其中包含引發的異常。否則,將返回 Ok,其中包含函式的結果。

預設情況下,當 Wasm 調用最終拋出異常的 JS 函式時,wasm-bindgen 將不會採取任何動作。目前 Wasm 規範不支援堆疊回溯,因此 Rust 程式碼將不會執行解構函式。這不幸地可能會導致 Rust 中出現記憶體洩漏,但一旦 Wasm 實現了捕捉異常,我們一定會新增支援!