Skip to content

serde(flatten) breaks metadata propagation in errors #80

@zegelin

Description

@zegelin

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions