pub fn deserialization_error(error: &impl std::fmt::Display) -> String {
let error = error.to_string();
let expected = || {
error
.rsplit_once(", expected ")
.map(|(_, expected)| expected)
};
if error.starts_with("invalid type:") {
match expected() {
Some(expected) => {
format!("a configuration value has the wrong type; expected {expected}")
}
None => "a configuration value has the wrong type; check the documented field types"
.to_string(),
}
} else if error.starts_with("invalid value:") || error.starts_with("unknown variant ") {
match expected() {
Some(expected) => {
format!("a configuration value is not supported; expected {expected}")
}
None => "a configuration value is not supported; check the documented allowed values"
.to_string(),
}
} else if let Some(rest) = error.strip_prefix("unknown field ") {
let token = rest
.rsplit_once(", expected ")
.map_or(rest, |(token, _)| token);
let token = token.split(" at line ").next().unwrap_or_default();
let name = option_name(token).map_or(String::new(), |name| format!(" {name}"));
match expected() {
Some(expected) => {
format!("the configuration contains an unknown field{name}; expected {expected}")
}
None => format!(
"the configuration contains an unknown field{name}; check the documented option names"
),
}
} else if error.starts_with("invalid length ")
|| error.starts_with("missing field ")
|| error.starts_with("duplicate field ")
{
error
} else {
"the configuration could not be parsed; check its syntax and documented options".to_string()
}
}
fn option_name(token: &str) -> Option<&str> {
let name = token.strip_prefix('`')?.strip_suffix('`')?;
let plain = name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'));
(!name.is_empty() && name.len() <= 64 && plain).then_some(token)
}
#[cfg(test)]
mod tests {
use super::deserialization_error;
use crate::format::avro::{AvroEncoderConfig, AvroUpdateFormat};
use serde_json::json;
#[test]
fn rejected_input_is_left_out_and_the_expected_part_stays() {
#[derive(Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(dead_code)]
struct Options {
update_format: Option<AvroUpdateFormat>,
threads: Option<usize>,
}
let cases = [
(json!("hunter2"), "wrong type; expected struct Options"),
(
json!({"update_format": "hunter2"}),
"not supported; expected one of `raw`, `debezium`",
),
(json!({"threads": "hunter2"}), "wrong type; expected usize"),
];
for (config, expected) in cases {
let error = serde_json::from_value::<Options>(config).unwrap_err();
let reason = deserialization_error(&error);
assert!(!reason.contains("hunter2"), "{reason}");
assert!(reason.contains(expected), "{reason}");
}
let error = serde_json::from_value::<Options>(json!({"treads": true})).unwrap_err();
assert_eq!(
deserialization_error(&error),
"the configuration contains an unknown field `treads`; expected `update_format` or `threads`"
);
let error = serde_json::from_value::<Options>(json!({"a b": true})).unwrap_err();
assert!(!deserialization_error(&error).contains("a b"));
}
#[test]
fn a_flattened_config_keeps_the_category() {
let error =
serde_json::from_value::<AvroEncoderConfig>(json!({"hunter2": true})).unwrap_err();
assert_eq!(
deserialization_error(&error),
"the configuration contains an unknown field `hunter2`; check the documented option names"
);
}
#[test]
fn positions_and_schema_field_names_stay() {
let error = serde_json::from_str::<AvroEncoderConfig>(
r#"{"namespace": "hunter2", "namespace": "a"}"#,
)
.unwrap_err();
assert_eq!(
deserialization_error(&error),
"duplicate field `namespace` at line 1 column 36"
);
#[derive(Debug, serde::Deserialize)]
#[allow(dead_code)]
struct Required {
key: String,
}
let error = serde_json::from_str::<Required>(r#"{"hunter2": "x"}"#).unwrap_err();
assert_eq!(
deserialization_error(&error),
"missing field `key` at line 1 column 16"
);
}
#[test]
fn custom_errors_are_not_copied() {
for error in ["custom error: hunter2", "hunter2, expected hunter2"] {
let reason = deserialization_error(&error);
assert!(!reason.contains("hunter2"), "{reason}");
assert!(reason.contains("check its syntax"), "{reason}");
}
}
}