Skip to content

Commit 681b820

Browse files
authored
Improve error message when using flatten with types other than struct or map (#27)
1 parent 3bf2a8c commit 681b820

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

src/private.rs

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,20 +42,31 @@ pub fn inline_if_unnamed(
4242

4343
struct FlattenError(Cow<'static, str>);
4444

45+
macro_rules! bail {
46+
($msg:expr) => {
47+
return Err(FlattenError($msg.into()))
48+
};
49+
}
50+
4551
fn flatten_impl(properties: &mut Properties, required: &mut Required, schema: SchemaKind) -> Result<(), FlattenError> {
4652
let mut obj = match schema {
4753
SchemaKind::Type(Type::Object(obj)) => obj,
54+
SchemaKind::Type(Type::String(_)) => bail!("can only flatten structs and maps (got a string)"),
55+
SchemaKind::Type(Type::Number(_)) => bail!("can only flatten structs and maps (got a number)"),
56+
SchemaKind::Type(Type::Integer(_)) => bail!("can only flatten structs and maps (got an integer)"),
57+
SchemaKind::Type(Type::Array(_)) => bail!("can only flatten structs and maps (got a sequence)"),
58+
SchemaKind::Type(Type::Boolean {}) => bail!("can only flatten structs and maps (got a bool)"),
59+
4860
SchemaKind::OneOf { .. } => {
49-
return Err(FlattenError(
50-
"#[serde(flatten)] is currently not supported for enums with non-unit variants".into()
51-
))
61+
bail!("flatten for enums with non-unit variants is currently unsupported")
5262
},
53-
_ => return Err(FlattenError("Expected object".into()))
63+
64+
_ => bail!("unsupported schema type, can only flatten structs and maps")
5465
};
5566

5667
while let Some((prop_name, prop_schema)) = obj.properties.pop() {
5768
if properties.contains_key(&prop_name) {
58-
return Err(FlattenError(format!("Duplicate property name {}", prop_name).into()));
69+
bail!(format!("Duplicate property name {}", prop_name));
5970
}
6071
properties.insert(prop_name, prop_schema);
6172
}

0 commit comments

Comments
 (0)