Skip to main content

wasm_toolkit/
common.rs

1use js_sys::JSON;
2use wasm_bindgen::{JsCast, JsValue};
3use web_sys::DomException;
4
5use crate::{WasmToolkitError, WasmToolkitResult};
6
7pub struct WasmToolkitCommon;
8
9impl WasmToolkitCommon {
10    pub fn stringify(obj: &JsValue) -> WasmToolkitResult<String> {
11        JSON::stringify(obj)
12            .or(Err(WasmToolkitError::UnableToStringifyJsValue))
13            .map(|value| value.as_string().ok_or(WasmToolkitError::JsStringNotValid))?
14    }
15
16    /// Converts the JsValue error into a string.
17    /// First checks if the error is a [DomException::message] first
18    /// if not try to convert the error using [JSON::stringify] and if that fails
19    /// just return an [WasmToolkitError::UnableToStringifyJsValue] error
20    pub fn exception_or_stringify(error: &JsValue) -> String {
21        if let Some(exception) = Self::as_dom_exception(error) {
22            exception.message()
23        } else {
24            Self::ok_err_as_string(Self::stringify(error))
25        }
26    }
27
28    pub fn as_dom_exception(error: &JsValue) -> Option<DomException> {
29        error.dyn_ref::<DomException>().cloned()
30    }
31
32    pub fn ok_err_as_string(result: WasmToolkitResult<String>) -> String {
33        match result {
34            Ok(value) => value,
35            Err(error) => error.to_string(),
36        }
37    }
38}