Skip to content

Commit cf3c014

Browse files
Add useful error message when an unsupported yaml hash key is found
1 parent 160d8a4 commit cf3c014

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/file/format/yaml.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ fn from_yaml_value(
5050
match key {
5151
yaml::Yaml::String(k) => m.insert(k.to_owned(), from_yaml_value(uri, value)?),
5252
yaml::Yaml::Integer(k) => m.insert(k.to_string(), from_yaml_value(uri, value)?),
53-
_ => unreachable!(),
53+
other => Err(Box::new(UnsupportedHashKeyError(format!("{other:?}"))))?,
5454
};
5555
}
5656
Ok(Value::new(uri, ValueKind::Table(m)))
@@ -103,3 +103,22 @@ impl Error for FloatParsingError {
103103
"Floating point number parsing failed"
104104
}
105105
}
106+
107+
#[derive(Debug, Clone)]
108+
struct UnsupportedHashKeyError(String);
109+
110+
impl fmt::Display for UnsupportedHashKeyError {
111+
fn fmt(&self, format: &mut fmt::Formatter<'_>) -> fmt::Result {
112+
write!(
113+
format,
114+
"Cannot parse {} because it is an unsupported hash key type",
115+
self.0
116+
)
117+
}
118+
}
119+
120+
impl Error for UnsupportedHashKeyError {
121+
fn description(&self) -> &str {
122+
"Unsupported yaml hash key found"
123+
}
124+
}

tests/testsuite/file_yaml.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -340,8 +340,9 @@ fn yaml() {
340340
}
341341

342342
#[test]
343-
#[should_panic]
344-
fn test_yaml_parsing_unsupported_hash() {
343+
/// We only support certain types as keys to a yaml hash, this test ensures
344+
/// we communicate that to the user effectively.
345+
fn test_yaml_parsing_unsupported_hash_has_useful_error_message() {
345346
let result = Config::builder()
346347
.add_source(File::from_str(
347348
r#"
@@ -352,4 +353,8 @@ inner_vec:
352353
))
353354
.build();
354355
assert!(result.is_err());
356+
assert_data_eq!(
357+
result.unwrap_err().to_string(),
358+
str!["Cannot parse Array([Integer(1), Integer(2)]) because it is an unsupported hash key type"]
359+
);
355360
}

0 commit comments

Comments
 (0)