serde_plain/
error.rs

1use serde::{de, ser};
2use std::fmt;
3
4use std::error;
5
6/// Errors created from this crate.
7#[derive(Debug, Clone)]
8pub enum Error {
9    /// An impossible / unsupported operation was attempted.
10    ImpossibleSerialization(&'static str),
11    /// A certain deserialization is impossible.
12    ImpossibleDeserialization(&'static str),
13    /// Raised when parsing errors happen during deserialization.
14    Parse(&'static str, String),
15    /// An arbitrary error message.
16    Message(String),
17}
18
19impl ser::Error for Error {
20    fn custom<T: fmt::Display>(msg: T) -> Error {
21        Error::Message(msg.to_string())
22    }
23}
24
25impl de::Error for Error {
26    fn custom<T: fmt::Display>(msg: T) -> Error {
27        Error::Message(msg.to_string())
28    }
29}
30
31impl error::Error for Error {}
32
33impl fmt::Display for Error {
34    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
35        match *self {
36            Error::ImpossibleSerialization(ty) => {
37                write!(f, "cannot serialize non primitive type {}", ty)
38            }
39            Error::ImpossibleDeserialization(ty) => {
40                write!(f, "cannot deserialize to non primitive type {}", ty)
41            }
42            Error::Parse(ref ty, ref msg) => write!(f, "cannot parse {}: {}", ty, msg),
43            Error::Message(ref msg) => write!(f, "{}", msg.as_str()),
44        }
45    }
46}