web_extensions/
error.rs

1use gloo_utils::format::JsValueSerdeExt;
2use thiserror::Error;
3use wasm_bindgen::{convert::FromWasmAbi, describe::WasmDescribe, prelude::*};
4
5#[derive(Debug, Error)]
6pub enum Error {
7    #[error("JavaScript error: {0:?}")]
8    Js(JsValue),
9    #[error(transparent)]
10    JsonDeserialization(serde_json::Error),
11    #[error(transparent)]
12    JsonSerialization(serde_json::Error),
13    #[error("Unable to convert JS value to an JS object")]
14    ObjectConversion,
15}
16
17impl From<JsValue> for Error {
18    fn from(err: JsValue) -> Self {
19        Self::Js(err)
20    }
21}
22
23#[derive(Debug)]
24pub enum FromWasmAbiResult<T, E> {
25    /// Contains the success value
26    Ok(T),
27
28    /// Contains the error value
29    Err(E),
30}
31
32impl<T, E> From<FromWasmAbiResult<T, E>> for Result<T, E> {
33    fn from(result: FromWasmAbiResult<T, E>) -> Self {
34        match result {
35            FromWasmAbiResult::Ok(v) => Ok(v),
36            FromWasmAbiResult::Err(e) => Err(e),
37        }
38    }
39}
40
41impl<T, E> From<Result<T, E>> for FromWasmAbiResult<T, E> {
42    fn from(result: Result<T, E>) -> Self {
43        match result {
44            Ok(v) => Self::Ok(v),
45            Err(e) => Self::Err(e),
46        }
47    }
48}
49
50pub type SerdeFromWasmAbiResult<T> = FromWasmAbiResult<T, serde_json::Error>;
51
52impl<T> WasmDescribe for SerdeFromWasmAbiResult<T> {
53    #[inline]
54    fn describe() {
55        JsValue::describe()
56    }
57}
58impl<T: for<'a> serde::Deserialize<'a>> FromWasmAbi for SerdeFromWasmAbiResult<T> {
59    type Abi = u32;
60
61    #[inline]
62    unsafe fn from_abi(js: u32) -> Self {
63        JsValue::from_abi(js).into_serde().into()
64    }
65}