wasm_bindgen_utils/result.rs
1use tsify::Tsify;
2use crate::impl_wasm_traits;
3use serde::{Serialize, Deserialize};
4
5/// A struct that holds info of a rust error that is serializable
6/// natively to JS/TS through wasm bindgen, so [Result::Err] variants
7/// of binding functions can return normally in JS/TS instead of throwing.
8///
9/// Rust errors should impl [Into] trait to this struct, handling how the
10/// the rust error would translate into this struct.
11#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Tsify)]
12#[serde(rename_all = "camelCase")]
13pub struct WasmEncodedError {
14 /// A short msg of the error, which usually is a direct
15 /// conversion from rust error by `Display` or `Debug` traits
16 pub msg: String,
17 /// Contains the detailed human readable msg of the error
18 pub readable_msg: String,
19}
20impl_wasm_traits!(WasmEncodedError);
21
22/// A generic result enum that holds info of a rust [Result] that is
23/// serializable natively to JS/TS through wasm bindgen, so binding
24/// functions can return it normally in JS/TS instead of throwing.
25///
26/// Used in [wasm_bindgen_utils_macros::wasm_export!] as the returning
27/// type of exporting wasm binding functions.
28#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Tsify)]
29#[serde(untagged)]
30pub enum WasmEncodedResult<T> {
31 /// Success variant that contains an instance of T in
32 /// `value`field with a [Option::None] `error` field
33 Success {
34 value: T,
35 #[tsify(type = "undefined")]
36 error: Option<WasmEncodedError>,
37 },
38 /// Error variant that contains an instance of [WasmEncodedError]
39 /// in `error` field with a [Option::None] `value` field
40 Err {
41 #[tsify(type = "undefined")]
42 value: Option<T>,
43 error: WasmEncodedError,
44 },
45}
46impl_wasm_traits!(WasmEncodedResult<T>);
47
48impl<T> WasmEncodedResult<T> {
49 /// Creates a success instance from the given type
50 pub fn success(value: T) -> Self {
51 WasmEncodedResult::Success { value, error: None }
52 }
53 /// Creates an error instance from the given type
54 pub fn error<E: Into<WasmEncodedError>>(err: E) -> Self {
55 WasmEncodedResult::Err {
56 value: None,
57 error: err.into(),
58 }
59 }
60}
61
62impl<T, E: Into<WasmEncodedError>> From<Result<T, E>> for WasmEncodedResult<T> {
63 fn from(result: Result<T, E>) -> Self {
64 match result {
65 Ok(value) => Self::success(value),
66 Err(err) => Self::error(err),
67 }
68 }
69}