-
Notifications
You must be signed in to change notification settings - Fork 46
serde(flatten) breaks metadata propagation in errors #80
Copy link
Copy link
Closed
Description
When using Figment with nested structs, some of which have #[serde(flatten)] attached, any error that occurs while loading the config for the nested flattened keys wont have any context info attached.
In the following examples the test.toml config is invalid -- a string is specified where a u32 is expected. In the first example flatten isn't used. In the second, the intermediate enum is flattened on the root struct.
use figment::{Figment, providers::{Toml, Format}};
use serde::Deserialize;
fn main() {
// example without flatten
let err = figment::Jail::try_with(|jail| {
#[derive(Clone, Deserialize, Debug)]
struct TcpConfig {
timeout: u32,
}
#[derive(Clone, Deserialize, Debug)]
#[serde(rename_all = "lowercase")]
enum PortConfig {
Tcp(TcpConfig)
}
#[derive(Clone, Deserialize, Debug)]
struct Config {
port: PortConfig,
}
jail.create_file("test.toml", r#"
port.tcp.timeout = "not a valid u32"
"#)?;
Figment::from(Toml::file("test.toml"))
.extract::<Config>().map(|c| ())
}).err().expect("should fail");
println!("{err}");
// example with flatten
let err = figment::Jail::try_with(|jail| {
#[derive(Clone, Deserialize, Debug)]
struct TcpConfig {
timeout: u32,
}
#[derive(Clone, Deserialize, Debug)]
#[serde(rename_all = "lowercase")]
enum PortConfig {
Tcp(TcpConfig)
}
#[derive(Clone, Deserialize, Debug)]
struct Config {
#[serde(flatten)]
port: PortConfig,
}
jail.create_file("test.toml", r#"
tcp.timeout = "not a valid u32"
"#)?;
Figment::from(Toml::file("test.toml"))
.extract::<Config>().map(|c| ())
}).err().expect("should fail");
println!("{err}");
}
When run the output is:
invalid type: found string "not a valid u32", expected u32 for key "default.port.tcp.timeout" in /tmp/.tmpzvTfAI/test.toml TOML file
invalid type: found string "not a valid u32", expected u32
The first error message is far more useful as it explains which key is invalid and which source file.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels