cargo_util_config/
error.rs1use std::fmt;
2
3use crate::{ArrayItemKeyPath, ConfigKey, ConfigValue, Definition};
4
5#[derive(Debug)]
7pub struct ConfigError {
8 error: anyhow::Error,
9 definition: Option<Definition>,
10}
11
12impl ConfigError {
13 pub(super) fn new(message: String, definition: Definition) -> ConfigError {
14 ConfigError {
15 error: anyhow::Error::msg(message),
16 definition: Some(definition),
17 }
18 }
19
20 pub fn expected(key: &ConfigKey, expected: &str, found: &ConfigValue) -> ConfigError {
21 ConfigError {
22 error: anyhow::anyhow!(
23 "`{}` expected {}, but found a {}",
24 key,
25 expected,
26 found.desc()
27 ),
28 definition: Some(found.definition().clone()),
29 }
30 }
31
32 pub(super) fn is_missing_field(&self) -> bool {
33 self.error.downcast_ref::<MissingFieldError>().is_some()
34 }
35
36 pub(super) fn missing(key: &ConfigKey) -> ConfigError {
37 ConfigError {
38 error: anyhow::anyhow!("missing config key `{}`", key),
39 definition: None,
40 }
41 }
42
43 pub(super) fn with_key_context(
44 self,
45 key: &ConfigKey,
46 definition: Option<Definition>,
47 ) -> ConfigError {
48 ConfigError {
49 error: anyhow::Error::from(self)
50 .context(format!("could not load config key `{}`", key)),
51 definition: definition,
52 }
53 }
54
55 pub(super) fn with_array_item_key_context(
56 self,
57 key: &ArrayItemKeyPath,
58 definition: Option<Definition>,
59 ) -> ConfigError {
60 ConfigError {
61 error: anyhow::Error::from(self).context(format!("failed to parse config at `{key}`")),
62 definition,
63 }
64 }
65}
66
67impl std::error::Error for ConfigError {
68 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
69 self.error.source()
70 }
71}
72
73impl fmt::Display for ConfigError {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 if let Some(definition) = &self.definition {
76 write!(f, "error in {}: {}", definition, self.error)
77 } else {
78 self.error.fmt(f)
79 }
80 }
81}
82
83#[derive(Debug)]
84struct MissingFieldError(String);
85
86impl fmt::Display for MissingFieldError {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 write!(f, "missing field `{}`", self.0)
89 }
90}
91
92impl std::error::Error for MissingFieldError {}
93
94impl serde::de::Error for ConfigError {
95 fn custom<T: fmt::Display>(msg: T) -> Self {
96 ConfigError {
97 error: anyhow::Error::msg(msg.to_string()),
98 definition: None,
99 }
100 }
101
102 fn missing_field(field: &'static str) -> Self {
103 ConfigError {
104 error: anyhow::Error::new(MissingFieldError(field.to_string())),
105 definition: None,
106 }
107 }
108}
109
110impl From<anyhow::Error> for ConfigError {
111 fn from(error: anyhow::Error) -> Self {
112 ConfigError {
113 error,
114 definition: None,
115 }
116 }
117}