yaml_config/
error.rs

1//! Errors returned by config.
2//!
3//! The primary error returned will be `ParseError`. `ParseError` wraps a number of different
4//! types of sub-errors that give more information.
5//!
6//!
7use std::env::VarError;
8use std::fmt;
9use std::io::Error;
10use yaml_rust::scanner::ScanError;
11/// Defines a ParseError.
12///
13/// `ParseError` is a wrapper around several different kinds of sub-errors that may occur. The goal
14/// is to give the user what they need without overburdening them with match statements.
15///
16/// **Examples**
17///
18/// ```rust
19/// use yaml_config::error::ParseError;
20/// let error = ParseError { module: "some_mod".to_string(), message: "something broke!".to_string() };
21/// ```
22#[derive(Debug)]
23pub struct ParseError {
24    pub module: String,
25    pub message: String,
26}
27
28impl fmt::Display for ParseError {
29    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
30        write!(f, "{}: {}", self.module, self.message)
31    }
32}
33
34impl From<ScanError> for ParseError {
35    fn from(error: ScanError) -> Self {
36        ParseError {
37            module: String::from("yaml_rust::scanner"),
38            message: error.to_string(),
39        }
40    }
41}
42
43impl From<VarError> for ParseError {
44    fn from(error: VarError) -> Self {
45        ParseError {
46            module: String::from("std::env"),
47            message: error.to_string(),
48        }
49    }
50}
51
52impl From<Error> for ParseError {
53    fn from(error: Error) -> Self {
54        ParseError {
55            module: String::from("std::io"),
56            message: error.to_string(),
57        }
58    }
59}
60
61#[cfg(test)]
62mod test {
63    use crate::ParseError;
64    use std::env::VarError;
65    use std::io::Error;
66
67    #[test]
68    fn test_display_trait() {
69        let error = ParseError {
70            module: "test::test".to_string(),
71            message: "test error".to_string(),
72        };
73        assert_eq!(format!("{}", error), "test::test: test error")
74    }
75
76    // ScanError cant be tested due to private fields.
77
78    #[test]
79    fn test_var_error() {
80        let error = ParseError::from(VarError::NotPresent);
81        assert_eq!(
82            format!("{}", error),
83            "std::env: environment variable not found"
84        );
85    }
86
87    #[test]
88    fn test_error() {
89        let error = ParseError::from(Error::new(std::io::ErrorKind::Unsupported, "bad news"));
90        assert_eq!(format!("{}", error), "std::io: bad news");
91    }
92}