WebAssembly Debugging
Debugging WebAssembly starts with the error name. The name tells you which stage failed.
Catch a trap
Divide by zero traps. The catch logs the error name.
try {
instance.exports.divide(10, 0);
} catch (error) {
console.log(error.name);
}Time repeated calls
The timer line prints a real time. It changes each run.
console.time("calls");
for (let i = 0; i < 100; i++) {
instance.exports.divide(10, 2);
}
console.timeEnd("calls");
console.log("100 calls done");Example
const B64 = "AGFzbQEAAAABCgJgAABgAn9/AX8DAwIAAQcRAgRib29tAAAGZGl2aWRlAAEKDQIDAAALBwAgACABbQs=";
(async () => {
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes, {});
try {
instance.exports.divide(10, 0);
} catch (error) {
console.log(error.name);
}
console.time("calls");
for (let i = 0; i < 1000; i++) {
instance.exports.divide(10, 2);
}
console.timeEnd("calls");
console.log("1000 calls done");
})();Key points
- Debugging is the work of finding why a module failed.
- Use try and catch around a call that may trap.
- Use console.time to time repeated calls.
- Log the error name, not just the message.
- The demo module below exports divide, which traps on zero.
- A trap name points at the failing call.
In this example, the code decodes the module bytes from B64 and instantiates the module. It tries divide with 10 and 0, catches the trap, and logs the error name. It then times one thousand divide calls and logs that the calls ran. The timer line prints a real time, so it is not listed here.
Note
the timer prints a real time that changes each run.
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 should you log first when a Wasm call traps?