Enhance WASM Error Handling with Structured Error Information #10

Closed
opened 2026-03-11 18:07:41 +03:00 by NiXTheDev · 0 comments
NiXTheDev commented 2026-03-11 18:07:41 +03:00 (Migrated from github.com)

Goal: Allow JavaScript consumers to get detailed error information (message, position, etc.) when compilation fails.

Currently, JsRegex::new returns Result<JsRegex, JsValue> where the error is a simple string. This loses span information.

Proposed Change:
Create a JsRegexError struct that can be converted to a JavaScript object with fields like message, start, end, and possibly kind. Use wasm_bindgen to export this struct.

Example:

#[wasm_bindgen]
pub struct JsRegexError {
    message: String,
    start: usize,
    end: usize,
}

#[wasm_bindgen]
impl JsRegexError {
    #[wasm_bindgen(getter)]
    pub fn message(&self) -> String { self.message.clone() }
    #[wasm_bindgen(getter)]
    pub fn start(&self) -> usize { self.start }
    #[wasm_bindgen(getter)]
    pub fn end(&self) -> usize { self.end }
}

Then in JsRegex::new, catch SpannedError and convert it to JsRegexError.

Benefits:

  • IDEs and tools can highlight error locations in the regex pattern.
  • Better debugging experience for JavaScript developers.

Implementation Steps:

  1. In wasm.rs, define JsRegexError with appropriate fields.
  2. Modify JsRegex::new to map SpannedError to JsRegexError.
  3. Add a try_compile method that returns Result<JsRegex, JsRegexError> (or keep new returning Result<JsRegex, JsValue> but with a richer error object).
  4. Update tests.
**Goal**: Allow JavaScript consumers to get detailed error information (message, position, etc.) when compilation fails. Currently, `JsRegex::new` returns `Result<JsRegex, JsValue>` where the error is a simple string. This loses span information. **Proposed Change**: Create a `JsRegexError` struct that can be converted to a JavaScript object with fields like `message`, `start`, `end`, and possibly `kind`. Use `wasm_bindgen` to export this struct. **Example**: ```rust #[wasm_bindgen] pub struct JsRegexError { message: String, start: usize, end: usize, } #[wasm_bindgen] impl JsRegexError { #[wasm_bindgen(getter)] pub fn message(&self) -> String { self.message.clone() } #[wasm_bindgen(getter)] pub fn start(&self) -> usize { self.start } #[wasm_bindgen(getter)] pub fn end(&self) -> usize { self.end } } ``` Then in `JsRegex::new`, catch `SpannedError` and convert it to `JsRegexError`. **Benefits**: - IDEs and tools can highlight error locations in the regex pattern. - Better debugging experience for JavaScript developers. **Implementation Steps**: 1. In wasm.rs, define JsRegexError with appropriate fields. 2. Modify JsRegex::new to map SpannedError to JsRegexError. 3. Add a try_compile method that returns Result<JsRegex, JsRegexError> (or keep new returning Result<JsRegex, JsValue> but with a richer error object). 4. Update tests.
Sign in to join this conversation.
No description provided.