WebAssembly Exceptions and Traps
A trap is an error that stops a Wasm function at once. JavaScript catches it as a RuntimeError.
An unreachable trap
This function does nothing but trap. Any call to it stops at once.
(module
(func (export "boom")
unreachable)
(func (export "divide") (param i32 i32) (result i32)
local.get 0
local.get 1
i32.div_s))Catch the trap in JavaScript
Call boom inside try. The catch logs the error name, which is RuntimeError.
try {
instance.exports.boom();
} catch (error) {
console.log(error.name);
}Divide by zero traps too
Divide with 10 and 0 traps. The catch logs the same error name.
try {
instance.exports.divide(10, 0);
} catch (error) {
console.log(error.name);
}Example
(async () => {
const B64 = "AGFzbQEAAAABCgJgAABgAn9/AX8DAwIAAQcRAgRib29tAAAGZGl2aWRlAAEKDQIDAAALBwAgACABbQs=";
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes);
try {
instance.exports.boom();
} catch (error) {
console.log(error.name);
}
try {
instance.exports.divide(10, 0);
} catch (error) {
console.log(error.name);
}
})();Key points
- A trap stops a Wasm function at once.
- Unreachable always traps when it runs.
- A divide by zero traps too.
- An out-of-bounds memory read traps too.
- JavaScript catches the trap with try and catch.
In this example, the bytes are decoded and started into an instance. Then boom is called inside try, and it traps, so the catch logs RuntimeError. Then divide is called with 10 and 0, and it traps too, so the catch logs RuntimeError again.
Note
A Rust panic reaches JavaScript as a RuntimeError.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What error does JavaScript catch when a Wasm function traps?