Skip to main content

asupersync_browser_core/
error.rs

1//! JS error conversions for the WASM boundary.
2//!
3//! Maps `WasmAbiFailure` and Rust panics to structured JS errors with
4//! deterministic codes and diagnostic metadata.
5//!
6//! This module focuses on deterministic boundary-error marshalling for
7//! bead `asupersync-3qv04.2.3`.
8
9use asupersync::types::WasmDispatchError;
10#[cfg(target_arch = "wasm32")]
11use wasm_bindgen::JsValue;
12
13/// Encode a dispatch error into the canonical JSON failure payload.
14#[must_use]
15pub fn dispatch_error_json(err: &WasmDispatchError) -> String {
16    let failure = err.to_failure();
17    serde_json::to_string(&failure).unwrap_or_else(|_| err.to_string())
18}
19
20/// Encode a dispatch error as `JsValue` for wasm-bindgen function boundaries.
21#[cfg(target_arch = "wasm32")]
22#[must_use]
23pub fn dispatch_error_js(err: &WasmDispatchError) -> JsValue {
24    JsValue::from_str(&dispatch_error_json(err))
25}
26
27#[cfg(test)]
28mod tests {
29    use super::dispatch_error_json;
30    use asupersync::types::wasm_abi::WasmHandleError;
31    use asupersync::types::{
32        WasmAbiErrorCode, WasmAbiFailure, WasmAbiRecoverability, WasmDispatchError,
33    };
34
35    #[test]
36    fn invalid_request_maps_to_decode_failure_payload() {
37        let err = WasmDispatchError::InvalidRequest {
38            reason: "malformed payload".to_string(),
39        };
40        let encoded = dispatch_error_json(&err);
41        let decoded: WasmAbiFailure = serde_json::from_str(&encoded).expect("decode failure json");
42
43        assert_eq!(decoded.code, WasmAbiErrorCode::DecodeFailure);
44        assert_eq!(decoded.recoverability, WasmAbiRecoverability::Permanent);
45        assert!(decoded.message.contains("invalid request"));
46    }
47
48    #[test]
49    fn handle_errors_map_to_invalid_handle_payload() {
50        let err = WasmDispatchError::Handle(WasmHandleError::SlotOutOfRange {
51            slot: 11,
52            table_size: 10,
53        });
54        let encoded = dispatch_error_json(&err);
55        let decoded: WasmAbiFailure = serde_json::from_str(&encoded).expect("decode failure json");
56
57        assert_eq!(decoded.code, WasmAbiErrorCode::InvalidHandle);
58        assert_eq!(decoded.recoverability, WasmAbiRecoverability::Permanent);
59        assert!(decoded.message.contains("handle error"));
60    }
61}