1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-05-23 19:00:13 +02:00

error-handling.md

This commit is contained in:
sakex 2023-07-24 17:30:21 +02:00
parent 7d411b7237
commit 4f8bc9061f
2 changed files with 55 additions and 0 deletions

View File

@ -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)

View File

@ -0,0 +1,54 @@
# Error handling
`Result<T, E>` 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<JsValue>`.
```rust
#[wasm_bindgen]
pub fn str_to_int(s: &str) -> Option<i32, JsValue> {
s.parse::<i32>()
.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<i32> {
s.parse::<i32>().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;
}
};
})();
```
<details>
* Click on the wasm output box to see the output
* `?` and other error handling toos also work
</details>