Catch panic in Wasm

I expected this code to return "error" but instead it panics:

#[wasm_bindgen]
pub fn foo() -> String {
    let res = std::panic::catch_unwind(|| panic!());
    match res {
        Ok(_) => "success".to_string(),
        Err(_) => "error".to_string(),
    }
}

So it seems like std::panic::catch_unwind has no effect when targeting Wasm. Is this documented somewhere?

Is there another way to catch the panic?

In short, wasm32-unknown-unknown is panic="abort" by default:

2 Likes

Thanks for the links!

At least I just figured out that I can catch the abort at the javascript side with normal try catch.

1 Like

Note that when you catch an exception on the javascript side, it is not safe to call any method on that specific wasm instance anymore. You need to recreate the wasm instance from scratch. Because of panic=abort, no cleanup code gets run, which may mean that unsafe code has left values in an inconsistent state that will result in memory unsafety when you try to use them again.

The C unwind proposal doesn't help with this by the way as it is WASM itself that doesn't currently support running any code on unwinding.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.