envy/
error.rs

1//! Error types
2use serde::de::Error as SerdeError;
3use std::{error::Error as StdError, fmt};
4
5/// Types of errors that may result from failed attempts
6/// to deserialize a type from env vars
7#[derive(Debug, Clone, PartialEq)]
8pub enum Error {
9    MissingValue(&'static str),
10    Custom(String),
11}
12
13impl StdError for Error {}
14
15impl fmt::Display for Error {
16    fn fmt(
17        &self,
18        fmt: &mut fmt::Formatter,
19    ) -> fmt::Result {
20        match *self {
21            Error::MissingValue(field) => write!(fmt, "missing value for field {}", field),
22            Error::Custom(ref msg) => write!(fmt, "{}", msg),
23        }
24    }
25}
26
27impl SerdeError for Error {
28    fn custom<T: fmt::Display>(msg: T) -> Self {
29        Error::Custom(format!("{}", msg))
30    }
31
32    fn missing_field(field: &'static str) -> Error {
33        Error::MissingValue(field)
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    fn impl_std_error<E: StdError>(_: E) {}
42
43    #[test]
44    fn error_impl_std_error() {
45        impl_std_error(Error::MissingValue("foo_bar"));
46        impl_std_error(Error::Custom("whoops".into()))
47    }
48
49    #[test]
50    fn error_display() {
51        assert_eq!(
52            format!("{}", Error::MissingValue("foo_bar")),
53            "missing value for field foo_bar"
54        );
55
56        assert_eq!(format!("{}", Error::Custom("whoops".into())), "whoops")
57    }
58}