expression

Catch a JavaScript exception inside Rust

Imported JavaScript functions may throw. The catch attribute lets supported binding signatures return Result instead of letting an exception escape the Rust call. This fixture only parses small synthetic JSON strings; it does not evaluate arbitrary JavaScript. Expected result (NOT RUN): valid_json("[1,2]") returns true; valid_json("[") returns false. Common mistake: Declaring a fallible host import without the catch attribute and assuming it returns a Rust Result. Static Rust source module for the accompanying Cargo lab; not a standalone executable or ByteMind exercise.

Formal Syntax & Structure

rust syntaxrust
#[wasm_bindgen(catch, js_namespace = JSON, js_name = parse)]

Working Example

Example Snippetrust
use wasm_bindgen::prelude::*;#[wasm_bindgen]extern "C" {    #[wasm_bindgen(catch, js_namespace = JSON, js_name = parse)]    fn parse_json(text: &str) -> Result<JsValue, JsValue>;}#[wasm_bindgen]pub fn valid_json(text: &str) -> bool { parse_json(text).is_ok() }
Rust Reference