Course contentsShow
← Rust
Lesson 1836 of 1,91016. Specialized Runtime TargetsFree lesson

Wasm-Specific Error Handling

Translate Rust panic states into meaningful JavaScript exceptions or Wasm trap codes.

In this lesson, you will learn how to bridge the gap between Rust’s internal panic state and the JavaScript runtime by mapping architectural traps to catchable exceptions.

When a Rust program compiled to WebAssembly (Wasm) hits an unrecoverable panic!, the default behavior is a "trap." A trap immediately halts execution of the Wasm instance and bubbles an error up to the host environment (JavaScript). However, a generic RuntimeError: unreachable executed is often useless for debugging or user-facing feedback. To provide a better experience, we must transform these internal states into explicit, actionable signals.

Catching and Transmitting Panics

Since Wasm cannot "throw" an exception directly into JavaScript in the way a native JS function would, we use a two-pronged approach. First, we set a panic_hook to capture metadata before the runtime collapses.

use std::panic;

#[no_mangle]
pub extern "C" fn setup_panic_hook() {
    panic::set_hook(Box::new(|info| {
        // Here we could write to a shared memory buffer 
        // that JavaScript reads after the trap.
        console_error("Critical Rust failure: {}", info);
    }));
}

Translating Traps to JavaScript

For more granular error handling, avoid panicking on predictable edge cases. Instead, define an explicit "Result" interface across the Wasm boundary. By returning a numeric code or a pointer to an error string, you allow the JavaScript host to decide how to handle the failure:

  1. The Result Pattern: Return an integer where 0 represents success and negative values represent specific error codes.
  2. Buffer Inspection: If an error occurs, store an error message in a pre-allocated Wasm memory segment. When your JS receives a non-zero code, it reads the memory segment to construct a meaningful Error object.

By moving away from "trapping" and toward "reporting," you treat the Wasm boundary as a fault-tolerant interface rather than a black box. This transforms opaque crashes into controlled application flow, allowing your JavaScript to recover gracefully or prompt the user without crashing the entire module.

Key Takeaway: Rather than letting Rust panics cause silent Wasm traps, implement a panic hook to log metadata and adopt result-code patterns to allow JavaScript to handle errors programmatically.