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
56
57
58
//! Error types
use serde::de::Error as SerdeError;
use std::{error::Error as StdError, fmt};

/// Types of errors that may result from failed attempts
/// to deserialize a type from env vars
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
    MissingValue(&'static str),
    Custom(String),
}

impl StdError for Error {}

impl fmt::Display for Error {
    fn fmt(
        &self,
        fmt: &mut fmt::Formatter,
    ) -> fmt::Result {
        match *self {
            Error::MissingValue(field) => write!(fmt, "missing value for field {}", field),
            Error::Custom(ref msg) => write!(fmt, "{}", msg),
        }
    }
}

impl SerdeError for Error {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        Error::Custom(format!("{}", msg))
    }

    fn missing_field(field: &'static str) -> Error {
        Error::MissingValue(field)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn impl_std_error<E: StdError>(_: E) {}

    #[test]
    fn error_impl_std_error() {
        impl_std_error(Error::MissingValue("foo_bar"));
        impl_std_error(Error::Custom("whoops".into()))
    }

    #[test]
    fn error_display() {
        assert_eq!(
            format!("{}", Error::MissingValue("foo_bar")),
            "missing value for field foo_bar"
        );

        assert_eq!(format!("{}", Error::Custom("whoops".into())), "whoops")
    }
}