serde_wasm_bindgen/
error.rs

1use wasm_bindgen::prelude::*;
2
3/// A newtype that represents Serde errors as JavaScript exceptions.
4#[derive(Debug)]
5pub struct Error(JsValue);
6
7impl std::fmt::Display for Error {
8    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
9        #[wasm_bindgen]
10        extern "C" {
11            #[wasm_bindgen(js_name = String)]
12            pub fn to_string(value: &JsValue) -> String;
13        }
14
15        to_string(&self.0).fmt(f)
16    }
17}
18
19impl std::error::Error for Error {}
20
21impl Error {
22    /// Creates a JavaScript `Error` with a given message.
23    pub fn new<T: std::fmt::Display>(msg: T) -> Self {
24        Error(JsError::new(&msg.to_string()).into())
25    }
26}
27
28impl serde::ser::Error for Error {
29    fn custom<T: std::fmt::Display>(msg: T) -> Self {
30        Error::new(msg)
31    }
32}
33
34impl serde::de::Error for Error {
35    fn custom<T: std::fmt::Display>(msg: T) -> Self {
36        Error::new(msg)
37    }
38}
39
40/// This conversion is needed for `?` to just work when using wasm-bindgen
41/// imports that return JavaScript exceptions as `Result<T, JsValue>`.
42impl From<JsValue> for Error {
43    fn from(error: JsValue) -> Error {
44        Error(error)
45    }
46}
47
48// This conversion is needed for `?` to just work in wasm-bindgen exports
49// that return `Result<T, JsValue>` to throw JavaScript exceptions.
50impl From<Error> for JsValue {
51    fn from(error: Error) -> JsValue {
52        error.0
53    }
54}