Skip to main content

configulator/
error.rs

1use std::fmt;
2
3/// Errors that can occur during configuration loading.
4#[derive(Debug)]
5#[non_exhaustive]
6pub enum ConfigulatorError {
7    /// No config file was found in any of the specified paths.
8    #[cfg(feature = "file")]
9    FileNotFound,
10    /// Failed to read or parse a config file.
11    #[cfg(feature = "file")]
12    FileError(String),
13    /// Failed to parse a value from a string.
14    ParseError { field: String, value: String, message: String },
15    /// Validation failed.
16    ValidationError(Box<dyn std::error::Error + Send + Sync>),
17    /// A required configuration source had an issue.
18    #[cfg(feature = "cli")]
19    CLIError(String),
20}
21
22impl fmt::Display for ConfigulatorError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            #[cfg(feature = "file")]
26            Self::FileNotFound => write!(f, "config file not found"),
27            #[cfg(feature = "file")]
28            Self::FileError(msg) => write!(f, "file error: {msg}"),
29            Self::ParseError { field, value, message } => {
30                write!(f, "failed to parse field '{field}' value '{value}': {message}")
31            }
32            Self::ValidationError(err) => write!(f, "validation error: {err}"),
33            #[cfg(feature = "cli")]
34            Self::CLIError(msg) => write!(f, "CLI error: {msg}"),
35        }
36    }
37}
38
39impl std::error::Error for ConfigulatorError {
40    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
41        match self {
42            Self::ValidationError(err) => Some(err.as_ref()),
43            #[allow(unreachable_patterns)]
44            _ => None,
45        }
46    }
47}