From 4f8bc9061fde033ddc09c410d6159cc0a45668a8 Mon Sep 17 00:00:00 2001 From: sakex Date: Mon, 24 Jul 2023 17:30:21 +0200 Subject: [PATCH] error-handling.md --- src/SUMMARY.md | 1 + src/webassembly/error-handling.md | 54 +++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 src/webassembly/error-handling.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 033e9201..cdc8cf88 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -301,6 +301,7 @@ - [Import Method](webassembly/import-method.md) - [web-sys](webassembly/web-sys.md) - [Expose a method](webassembly/expose-method.md) +- [Error handling](webassembly/error-handling.md) - [Expose user-defined Rust types](webassembly/expose-rust-type.md) - [Borrow Checker](webassembly/borrow-checker.md) diff --git a/src/webassembly/error-handling.md b/src/webassembly/error-handling.md new file mode 100644 index 00000000..37a6a47b --- /dev/null +++ b/src/webassembly/error-handling.md @@ -0,0 +1,54 @@ +# Error handling + +`Result` is translated to javascript errors. Methods directly exposed and called from Javascript that return a `Result` +will automatically throw an error if the variant of the return value is `Result::Err`. `E` has to implement `Into`. + +```rust +#[wasm_bindgen] +pub fn str_to_int(s: &str) -> Option { + s.parse::() + .map_err(|_| JsValue::from_str("Failed to parse string")) +} +``` + +`Option` is converted to `undefined` in case of `None`. + +```rust +#[wasm_bindgen] +pub fn str_to_int(s: &str) -> Option { + s.parse::().ok() +} + +``` + +Javascript (click on the wasm output box) to parse the string: + +```javascript +import init, {set_panic_hook, str_to_int} from '/wasm/project.js'; + + +(async () => { + // Run the init method to initiate the WebAssembly module. + await init(); + set_panic_hook(); + const wasmoutput = document.querySelector('#wasmoutput'); + const input = document.createElement('input'); + input.type = 'text'; + document.body.appendChild(input); + wasmoutput.onclick = () => { + try { + wasmoutput.innerHTML = str_to_int(input.value); + } catch (e) { + wasmoutput.innerHTML = e; + } + }; +})(); +``` + + +
+ +* Click on the wasm output box to see the output +* `?` and other error handling toos also work + +
\ No newline at end of file