catlog_wasm/
result.rs

1//! Result of fallible computation that translates to/from JavaScript.
2
3use serde::{Deserialize, Serialize};
4use tsify_next::Tsify;
5
6/** A `Result`-like type that translates to/from JavaScript.
7
8In `wasm-bindgen`, returning a [`Result`] raises an exception in JavaScript when
9the `Err` variant is given:
10
11<https://rustwasm.github.io/docs/wasm-bindgen/reference/types/result.html>
12
13When an error should be handled in the UI, it is often more convenient to return
14an error value than to raise an exception. That's what this enum does.
15*/
16#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Tsify)]
17#[serde(tag = "tag", content = "content")]
18#[tsify(into_wasm_abi, from_wasm_abi)]
19pub enum JsResult<T, E> {
20    /// Contains the success value
21    Ok(T),
22
23    /// Contains the error value
24    Err(E),
25}
26
27impl<T, E> From<Result<T, E>> for JsResult<T, E> {
28    fn from(value: Result<T, E>) -> Self {
29        match value {
30            Result::Ok(x) => JsResult::Ok(x),
31            Result::Err(x) => JsResult::Err(x),
32        }
33    }
34}
35
36impl<T> From<Option<T>> for JsResult<T, ()> {
37    fn from(value: Option<T>) -> Self {
38        match value {
39            Option::Some(x) => JsResult::Ok(x),
40            Option::None => JsResult::Err(()),
41        }
42    }
43}