catch
catch
屬性允許捕獲 JavaScript 例外。這可以附加到任何匯入的函式或方法,並且該函式必須傳回 Result
,其中 Err
的有效負載為 JsValue
#![allow(unused)] 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 實作了捕獲例外的功能,我們一定也會新增支援!