Skip to content

Commit

Permalink
fix: Add key tracking for all error types
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Jan 10, 2025
1 parent 5852262 commit fd55144
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 5 deletions.
39 changes: 37 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,16 @@ pub enum ConfigError {
key: Option<String>,
},

/// Custom message
At {
/// Error being extended with a path
error: Box<ConfigError>,

/// The key in the configuration hash of this value (if available where the
/// error is generated).
key: Option<String>,
},

/// Custom message
Message(String),

Expand Down Expand Up @@ -130,7 +140,15 @@ impl ConfigError {
key: Some(key.into()),
},

_ => self,
Self::At { error, .. } => Self::At {
error,
key: Some(key.into()),
},

other => Self::At {
error: Box::new(other),
key: Some(key.into()),
},
}
}

Expand All @@ -157,8 +175,15 @@ impl ConfigError {
expected,
key: Some(concat(key)),
},
Self::At { error, key } => Self::At {
error,
key: Some(concat(key)),
},
Self::NotFound(key) => Self::NotFound(concat(Some(key))),
_ => self,
other => Self::At {
error: Box::new(other),
key: Some(concat(None)),
},
}
}

Expand Down Expand Up @@ -217,6 +242,16 @@ impl fmt::Display for ConfigError {
Ok(())
}

ConfigError::At { ref error, ref key } => {
write!(f, "{error}")?;

if let Some(ref key) = *key {
write!(f, " for key `{key}`")?;
}

Ok(())
}

ConfigError::FileParse { ref cause, ref uri } => {
write!(f, "{cause}")?;

Expand Down
10 changes: 8 additions & 2 deletions tests/testsuite/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,10 @@ fn test_get_missing_field() {
.unwrap();

let res = c.get::<InnerSettings>("inner");
assert_data_eq!(res.unwrap_err().to_string(), str!["missing field `value2`"]);
assert_data_eq!(
res.unwrap_err().to_string(),
str!["missing field `value2` for key `inner`"]
);
}

#[test]
Expand Down Expand Up @@ -342,5 +345,8 @@ fn test_deserialize_missing_field() {
.unwrap();

let res = c.try_deserialize::<Settings>();
assert_data_eq!(res.unwrap_err().to_string(), str!["missing field `value2`"]);
assert_data_eq!(
res.unwrap_err().to_string(),
str!["missing field `value2` for key `inner`"]
);
}
2 changes: 1 addition & 1 deletion tests/testsuite/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,6 @@ fn test_load_level_lowercase() {
assert!(s.is_err());
assert_data_eq!(
s.unwrap_err().to_string(),
str!["enum Level does not have variant constructor error"]
str!["enum Level does not have variant constructor error for key `log`"]
);
}

0 comments on commit fd55144

Please sign in to comment.