Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท Calling Between JS and Wasm

Traps and Errors

Learn every way WebAssembly can fail: CompileError, LinkError, RuntimeError traps, stack overflow, out of memory, and how to catch them. Includes the exception handling Tag and Exception API.

Things go wrong. A file is corrupted, an import is missing, a program divides by zero, a pointer runs off the end of memory. WebAssembly has a precise vocabulary for failure, and every failure reaches JavaScript as a normal exception that you can catch. Knowing which error means what tells you at once whether the bug is in your build, your loading code or your program logic.

Where errors come from

flowchart TD
    B["Bytes"] -->|"bad format or type error"| CE["WebAssembly.CompileError"]
    B --> L["Instantiate with imports"]
    L -->|"missing or mismatched import"| LE["WebAssembly.LinkError / TypeError"]
    L --> R["Call an export"]
    R -->|"trap while running"| RE["WebAssembly.RuntimeError"]
    R -->|"too much recursion / memory"| RG["RangeError"]
    R -->|"JavaScript import throws"| JS["The original exception"]
Stage Error Typical cause
Compile WebAssembly.CompileError Corrupt file, wrong MIME type truncation, invalid code, unsupported feature
Instantiate WebAssembly.LinkError Import has the wrong type, limits or mutability; missing function
Instantiate TypeError Import object missing, or a module name is not an object
Run WebAssembly.RuntimeError A trap
Run RangeError Call stack exhausted, memory or table growth failed
Run Any error An imported JavaScript function threw

Traps

A trap is WebAssembly's way of saying "this program did something it must not do, stop now". The current call is aborted, the host receives a RuntimeError, and control returns to the JavaScript code that called the export. The exact message text depends on the engine, so write code that checks the error type, never the message.

Operations that trap:

Operation Condition
unreachable Always
Integer div / rem Divisor is 0
i32.div_s INT_MIN / -1 (the result does not fit)
trunc conversions (i32.trunc_f64_s...) Value is NaN or out of range
Memory load / store Address plus size is outside the memory
memory.copy, fill, init Range out of bounds
call_indirect Index outside the table, null entry, or wrong signature
table.get, table.set Index out of bounds

Floating-point math never traps: dividing by zero yields Infinity or NaN.

Node.js Provoke every kind of trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Three points from the output: the trap in storeThenTrap did not undo the earlier store (there is no transaction), the instance remains usable, and load(65533) fails because the 4-byte read would cross the end of the page, even though the first byte is valid.

A trap can leave a module's data structures half updated (an allocator pointer moved, a list half linked). After a trap, either discard the instance and create a new one, or make sure your module is written so that every call can be safely abandoned.

Errors that are not traps

Stack overflow is a RangeError thrown by the host when recursion is too deep. Out of memory shows up as a RangeError from new WebAssembly.Memory, from memory.grow in JavaScript, or from instantiation when the requested minimum cannot be reserved; the Wasm instruction memory.grow instead returns -1. And a CompileError is how you will discover most feature mismatches: a module compiled with SIMD or threads running on an engine that lacks them.

Feature detection avoids that last case. WebAssembly.validate() on a tiny module that uses the feature tells you, without throwing:

JavaScript
// Does this engine support multi-value results? (a function returning two i32)
const multiValue = WebAssembly.validate(new Uint8Array([
  0,97,115,109, 1,0,0,0,
  1,6,1,0x60,0,2,0x7f,0x7f,        // type: () -> (i32, i32)
]));

Libraries such as wasm-feature-detect ship these small probes for every feature.

Exceptions: Tag and Exception

Traps are not exceptions: Wasm code cannot catch them. The exception handling feature (supported by all current engines) adds real, catchable exceptions to the language. A tag describes the payload types of an exception. Wasm uses the throw instruction with a tag, and try_table (or the older try/catch) to handle it. JavaScript sees the same objects as WebAssembly.Tag and WebAssembly.Exception, so an exception can cross the boundary in either direction. C++ and Rust compile their exceptions and panics to this mechanism.

This module declares a tag whose payload is one i32, exports it, and exports fail(x), which throws it:

Node.js Throwing a WebAssembly exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

An exception is distinct from a trap: e is a WebAssembly.Exception, not a RuntimeError, and carries typed data you can read with getArg.

Handling errors well

  • Catch at the boundary. Wrap calls into Wasm in try/catch, and convert errors into messages your application understands.
  • Branch on type. e instanceof WebAssembly.RuntimeError for traps, LinkError for bad imports, CompileError for bad files, RangeError for resource limits.
  • Report where it happened. e.stack lists frames such as wasm-function[3]:0x4b. With a name section or DWARF debug info (covered in the debugging chapter) these become real function names and source lines.
  • Validate before calling. Checking for a zero divisor or a negative length in JavaScript is cheap and gives a better message than a trap.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A module's import is missing from the import object's module. Which error?

    Imports are checked when the instance is created, before any code runs. A missing field is a LinkError; a missing module object is a TypeError.
  2. 2. Which operation never traps?

    Floating-point division follows IEEE 754 and gives Infinity or NaN.
  3. 3. After a trap, what is true about earlier memory writes?

    A trap aborts the call but does not undo state changes or destroy the instance.
  4. 4. How should code detect a trap?

    Messages vary between engines; the error type is stable.
  5. 5. What does memory.grow do inside Wasm when growth fails?

    The instruction returns -1. Only the JavaScript Memory.grow() throws a RangeError.

Summary

  • CompileError means a bad module, LinkError or TypeError bad imports, RuntimeError a trap, and RangeError a resource limit.
  • Traps come from unreachable, integer division errors, bad conversions, out-of-bounds memory or table access, and bad indirect calls.
  • A trap aborts the call but keeps the instance and its memory as they were at that moment.
  • Test error types, not message text, and validate arguments in JavaScript.
  • Exception handling adds typed, catchable exceptions (WebAssembly.Tag and WebAssembly.Exception) that cross the boundary.
  • Feature detection with WebAssembly.validate avoids CompileError on older engines.

Next: Compiling C to WebAssembly with Emscripten