Debugging¶
Before we write much more code, we will want to have some debugging tools in our belt for when things go wrong. Take a moment to review the reference page listing tools and approaches available for debugging Rust-generated WebAssembly.
Enable Logging for Panics¶
If our code panics, we want informative error messages to appear in the developer console.
Our wasm-pack-template
comes with an optional, enabled-by-default dependency on the console_error_panic_hook
crate that is configured in wasm-game-of-life/src/utils.rs
. All we need to do is install the hook in an initialization function or common code path. We can call it inside the Universe::new
constructor in wasm-game-of-life/src/lib.rs
:
1 2 3 4 5 |
|
Add Logging to our Game of Life¶
Let's use the console.log
function via the web-sys
crate to add some logging about each cell in our Universe::tick
function.
First, add web-sys
as a dependency and enable its "console"
feature in wasm-game-of-life/Cargo.toml
:
1 2 3 4 5 6 7 8 9 |
|
For ergonomics, we'll wrap the console.log
function up in a println!
-style macro:
1 2 3 4 5 6 7 8 |
|
Now, we can start logging messages to the console by inserting calls to log
in Rust code. For example, to log each cell's state, live neighbors count, and next state, we could modify wasm-game-of-life/src/lib.rs
like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
Using a Debugger to Pause Between Each Tick¶
For example, we can use the debugger to pause on each iteration of our renderLoop
function by placing a JavaScript debugger;
statement above our call to universe.tick()
.
1 2 3 4 5 6 7 8 9 |
|
This provides us with a convenient checkpoint for inspecting logged messages, and comparing the currently rendered frame to the previous one.
Exercises¶
-
Add logging to the
tick
function that records the row and column of each cell that transitioned states from live to dead or vice versa. -
Introduce a
panic!()
in theUniverse::new
method. Inspect the panic's backtrace in your Web browser's JavaScript debugger. Disable debug symbols, rebuild without theconsole_error_panic_hook
optional dependency, and inspect the stack trace again. Not as useful is it?