Skip to content

Commit

Permalink
Merge pull request #635 from epage/key
Browse files Browse the repository at this point in the history
fix: Add key tracking for all error types
  • Loading branch information
epage authored Jan 10, 2025
2 parents cc1ba8b + 7496699 commit d9e0197
Show file tree
Hide file tree
Showing 7 changed files with 288 additions and 67 deletions.
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

0 comments on commit d9e0197

Please sign in to comment.