Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Add key tracking for all error types #635

Merged
merged 5 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 54 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,21 @@ pub enum ConfigError {
key: Option<String>,
},

/// Custom message
At {
/// Error being extended with a path
error: Box<ConfigError>,

/// The URI that references the source that the value came from.
/// Example: `/path/to/config.json` or `Environment` or `etcd://localhost`
// TODO: Why is this called Origin but FileParse has a uri field?
origin: Option<String>,

/// The key in the configuration hash of this value (if available where the
/// error is generated).
key: Option<String>,
},

/// Custom message
Message(String),

Expand Down Expand Up @@ -130,7 +145,17 @@ impl ConfigError {
key: Some(key.into()),
},

_ => self,
Self::At { origin, error, .. } => Self::At {
error,
origin,
key: Some(key.into()),
},

other => Self::At {
error: Box::new(other),
origin: None,
key: Some(key.into()),
},
}
}

Expand All @@ -157,8 +182,17 @@ impl ConfigError {
expected,
key: Some(concat(key)),
},
Self::At { error, origin, key } => Self::At {
error,
origin,
key: Some(concat(key)),
},
Self::NotFound(key) => Self::NotFound(concat(Some(key))),
_ => self,
other => Self::At {
error: Box::new(other),
origin: None,
key: Some(concat(None)),
},
}
}

Expand Down Expand Up @@ -217,6 +251,24 @@ impl fmt::Display for ConfigError {
Ok(())
}

ConfigError::At {
ref error,
ref origin,
ref key,
} => {
write!(f, "{error}")?;

if let Some(ref key) = *key {
write!(f, " for key `{key}`")?;
}

if let Some(ref origin) = *origin {
write!(f, " in {origin}")?;
}

Ok(())
}

ConfigError::FileParse { ref cause, ref uri } => {
write!(f, "{cause}")?;

Expand Down
5 changes: 5 additions & 0 deletions tests/testsuite/deserialize-invalid-type.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"place": {
"name": "Torre di Pisa"
}
}
3 changes: 3 additions & 0 deletions tests/testsuite/deserialize-missing-field.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"inner": { "value": 42 }
}
Loading
Loading