0Pricing
WebAssembly (WASM) for High Performance Apps · 课时

跨越 WASM 边界的错误处理

使用 wasm-bindgen,让 Rust 的结果、选项和恐慌在进入 JavaScript 时得到妥善处理。

跨越 WASM 边界的错误处理 是 CoddyKit 上的免费 WebAssembly (WASM) for High Performance Apps 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebAssembly (WASM) for High Performance Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Errors Need a Bridge

Rust uses Result and Option for errors; JavaScript uses exceptions and null/undefined.

wasm-bindgen bridges these two worlds so failures surface naturally on each side.

Returning Result to JS

A Rust function returning Result<T, JsValue> becomes a JS function that either returns the value or throws.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn parse(input: &str) -> Result<i32, JsValue> {
    input.parse::<i32>()
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

Catching It in JavaScript

On the JS side, an Err arrives as a thrown exception, so wrap calls in try/catch.

try {
  const n = parse('abc');
} catch (e) {
  console.error('Parse failed:', e);
}

Mapping Custom Errors

Convert your own error types into a JsValue so JS gets a useful message. The ? operator plus map_err keeps this clean.

#[wasm_bindgen]
pub fn divide(a: i32, b: i32) -> Result<i32, JsValue> {
    if b == 0 {
        return Err(JsValue::from_str('division by zero'));
    }
    Ok(a / b)
}

Returning Option

Rust's Option<T> maps to a value or undefined in JS, perfect for nullable results.

#[wasm_bindgen]
pub fn first_char(s: &str) -> Option<char> {
    s.chars().next()
}

What Happens on Panic

A Rust panic in WASM aborts the module and is hard to debug, by default you get an unhelpful 'unreachable' error.

Panics should be rare; prefer Result for expected failures.

Better Panic Messages

The console_error_panic_hook crate forwards panic messages to the browser console, making debugging far easier.

#[wasm_bindgen(start)]
pub fn main() {
    console_error_panic_hook::set_once();
}

Result vs Panic

Choose deliberately:

  • Result, expected, recoverable errors (bad input, not found)
  • Panic, programmer bugs and invariants that should never break

Never use panics for normal control flow across the boundary.

Using a Custom Error Type

For richer errors, define a struct exported to JS, so JS can read fields instead of just a string.

#[wasm_bindgen]
pub struct AppError { pub code: i32 }

#[wasm_bindgen]
impl AppError {
    #[wasm_bindgen(getter)]
    pub fn code(&self) -> i32 { self.code }
}

Propagating with ?

Inside a function returning Result<_, JsValue>, the ? operator propagates errors cleanly when types convert.

#[wasm_bindgen]
pub fn run(input: &str) -> Result<i32, JsValue> {
    let n: i32 = input.parse().map_err(|_| JsValue::from_str('bad'))?;
    Ok(n * 2)
}

Best Practices Summary

For robust error handling:

  • Return Result<T, JsValue> so errors become JS exceptions
  • Return Option for nullable values
  • Install console_error_panic_hook for debuggable panics
  • Reserve panics for true bugs, use Result for expected failures

Quick Check

How does a Rust function returning Result<T, JsValue> behave when it returns Err and is called from JavaScript?

Recap

You now handle errors cleanly across the boundary:

  • Result becomes a JS throw; Option becomes value-or-undefined
  • Map custom errors into JsValue
  • Use console_error_panic_hook to debug panics
  • Prefer Result over panic for expected failures

Clear error semantics make Rust+WASM libraries pleasant and safe to consume from JS.

常见问题解答

「跨越 WASM 边界的错误处理」课时是免费的吗?

是的 — 「跨越 WASM 边界的错误处理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebAssembly (WASM) for High Performance Apps 课程的其余内容,请升级到 CoddyKit PRO。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。

「跨越 WASM 边界的错误处理」这节课中我会学到什么?

使用 wasm-bindgen,让 Rust 的结果、选项和恐慌在进入 JavaScript 时得到妥善处理。 你通过在浏览器中直接运行的动手代码来练习 WebAssembly (WASM) for High Performance Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebAssembly (WASM) for High Performance Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebAssembly (WASM) for High Performance Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「跨越 WASM 边界的错误处理」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebAssembly (WASM) for High Performance Apps 课中编写并运行代码吗?

能。每节 WebAssembly (WASM) for High Performance Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 为 WebAssembly 设置 Rust
  2. 为 WASM 编写 Rust 函数
  3. 使用 `wasm-bindgen` 高效实现 JS 互操作
  4. 跨越 WASM 边界的错误处理
← 返回 WebAssembly (WASM) for High Performance Apps