1use serde::de::Error as DeError;
2use serde::ser::Error as SerError;
3use std::{error::Error as StdError, fmt::Display};
4
5#[derive(Debug)]
6pub struct Error {
7 pub message: String,
8 pub cause: Option<Box<dyn StdError>>,
9}
10
11impl Error {
12 pub fn new(message: impl Into<String>, cause: Option<Box<dyn StdError>>) -> Self {
13 Error {
14 message: message.into(),
15 cause,
16 }
17 }
18}
19
20impl DeError for Error {
21 fn custom<T: std::fmt::Display>(msg: T) -> Self {
22 Error {
23 message: msg.to_string(),
24 cause: None,
25 }
26 }
27}
28
29impl SerError for Error {
30 fn custom<T>(msg: T) -> Self
31 where
32 T: Display,
33 {
34 Error {
35 message: msg.to_string(),
36 cause: None,
37 }
38 }
39}
40
41impl Display for Error {
42 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 if let Some(cause) = &self.cause {
44 return write!(f, "{}: {}", self.message, cause);
45 }
46 write!(f, "{}", self.message)
47 }
48}
49
50impl StdError for Error {}