error.rs
1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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")
}
}
}