error.rs 1.4 KB
use std::fmt::Display;
use wasm_bindgen::prelude::*;

type ParentError = Option<Box<dyn std::error::Error>>;

#[derive(Debug)]
pub(crate) struct Error {
    source: ParentError,
    message: String,
}

pub(crate) type Result<T> = std::result::Result<T, Error>;

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source.as_deref()
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error { source: Some(source), message } =>
                write!(f, "{}: {}", message, source),
            Error { source: None, message } => write!(f, "{}", message),
        }
    }
}

impl From<&str> for Error {
    fn from(message: &str) -> Self {
        Self { source: None, message: String::from(message) }
    }
}

impl From<JsValue> for Error {
    fn from(source: JsValue) -> Self {
        let source = js_sys::Error::from(source);

        let message = format!("[{}] {}", source.name(), source.message());
        let source = Error::from(message.as_str());

        Self { source: Some(Box::new(source))
             , message: String::from("WebSys Error")
        }
    }
}

impl From<serde_json::Error> for Error {
    fn from(source: serde_json::Error) -> Self {
        Self { source: Some(Box::new(source))
             , message: String::from("Serde Error")
        }
    }
}