⚠️ Handling Errors
In this example we'll see how to pattern match for the error and output the error message returned from Wasmer.
There will come a time when running a WebAssembly module will not work, and trying to figure out why it does not work can be a difficult task! In the current MVP of WebAssembly, debugging isn't explicitly defined for runtimes both in and out of the browser. So we'll have to write some error handling code ourselves.
In this example, we will load a WebAssembly module that purposely produces an error in its exported function call. The Host (our Rust application) will pattern match for the error and output the error message returned from Wasmer.
First we are going to want to initialize a new project. To do this we can navigate to our project folder, or create one. In this example, we will create a new project. Lets create it and navigate to it:
The final code for this example can be found on GitHub.
Please take a look at the setup steps for Rust.
We have to modify Cargo.toml
to add the Wasmer dependencies as shown below:
Now that we have everything set up, let's go ahead and try it out!
Handling the error
There is nothing special about the WASM module or the way we'll set it up.
The only things we'll need to do are:
Getting the exported function
Calling the function;
Handling the error.
Here is the easy part, getting and calling the function:
And here is the interesting part, handling the error:
Here we verify the result of calling the function to see if we actually got an error.
If we got an error we format a nice message containing information to help debug the problem:
The error message.
The error trace.
Running
We now have everything we need to run the WASM module, let's do it!
You should be able to run it using the cargo run
command. The output should look like this:
If you want to run the examples from the Wasmer repository codebase directly, you can also do:
Last updated