I've read through the Writing WebAssembly in Rust part of the Wasmtime guide. It's not clear to me how I can have a function called by the host trap using rust code. From reading the Func#wrap documentation, it mentions I can use Result<T, Trap>
to handle functions that can trap, but it also specifies that the WebAssembly return type in such a case is T
. So, my question is, how can I bubble up errors from a Wasm function written in Rust?
If you call a rust function, which returns Result<T, Trap>, from webassembly, it will either return T or cause a Trap (which will
interrupt the execution).
@Maciej Kot thank you for that. I'm still not entirely sure that answers my question, but that could well be because of my misunderstanding of terminology here. Just to clarify, I'm writing a Wasm function in Rust (e.g. compiling cdylib
using wasm32-unknown-unknown
target). So my question is, what should the signature of the Rust function be that gets compiled to Wasm, to be able to manually trigger traps/errors/exceptions from within that Rust/Wasm function, to allow whatever runtime is running the wasm code to catch those errors and distinguish them from regular return values of that function.
So it not a trap. Trap "poisons" current instance sometimes without chance of recovery. There is exception handling proposal for WebAssembly -- it might be a better fit. Basically you need to do it by yourself atm, e.g. as rust does: via your own "Result"-like structure for the layer between host and guest code.
Ah right, that's the context I was missing, so traps aren't the solution here, and exceptions aren't available yet. Using something like a serialized data structure which includes error details makes sense. Thank you @Yury Delendik.
Last updated: Nov 22 2024 at 16:03 UTC