0Pricing
WebAssembly (WASM) for High Performance Apps · Lesson

Error Handling Across the WASM Boundary

Handle Rust Results, Options, and panics cleanly when they cross into JavaScript using wasm-bindgen.

Error Handling Across the WASM Boundary is a free WebAssembly (WASM) for High Performance Apps lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the WebAssembly (WASM) for High Performance Apps learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Frequently asked questions

Is the “Error Handling Across the WASM Boundary” lesson free?

Yes — the full text of “Error Handling Across the WASM Boundary” is free to read here on the web, and the WebAssembly (WASM) for High Performance Apps course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the WebAssembly (WASM) for High Performance Apps course, upgrade to CoddyKit PRO.

What will I learn in “Error Handling Across the WASM Boundary”?

Handle Rust Results, Options, and panics cleanly when they cross into JavaScript using wasm-bindgen. You practise WebAssembly (WASM) for High Performance Apps with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start WebAssembly (WASM) for High Performance Apps?

No prior experience is required. WebAssembly (WASM) for High Performance Apps on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Error Handling Across the WASM Boundary” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this WebAssembly (WASM) for High Performance Apps lesson?

Yes. Every WebAssembly (WASM) for High Performance Apps lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Setting up Rust for WebAssembly
  2. Writing Rust Functions for WASM
  3. Efficient JS Interop with `wasm-bindgen`
  4. Error Handling Across the WASM Boundary
← Back to WebAssembly (WASM) for High Performance Apps