Skip to content

Commit

Permalink
feat!: Include key name in error (#73)
Browse files Browse the repository at this point in the history
* feat!: Include key name in error

* typo
  • Loading branch information
fasterthanlime authored Sep 22, 2024
1 parent 8049a7b commit 95408e4
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
2 changes: 1 addition & 1 deletion merde/examples/return-deserialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ where
T: OwnedValueDeserialize,
{
// here `s` is a `String`, but pretend we're making
// a network request intead — the point is is that we
// a network request instead — the point is is that we
// need to borrow from a local from the function body.
let value: Value = merde_json::from_str_via_value(&s).map_err(|e| e.to_static())?;
Ok(T::owned_from_value(Some(value))?)
Expand Down
5 changes: 4 additions & 1 deletion merde_core/src/deserialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,10 @@ where
Some(Value::Map(obj)) => {
let mut map = std::collections::HashMap::new();
for (key, val) in obj.iter() {
let parsed_key = K::from_str(key).map_err(|_| MerdeError::InvalidKey)?;
let parsed_key = K::from_str(key).map_err(|_| MerdeError::InvalidKey {
key: key.clone().into_static(),
type_name: std::any::type_name::<K>(),
})?;
let parsed_value = V::from_value_ref(Some(val))?;
map.insert(parsed_key, parsed_value);
}
Expand Down
13 changes: 10 additions & 3 deletions merde_core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ pub enum MerdeError {
MissingValue,

/// While calling out to [`FromStr::from_str`](std::str::FromStr::from_str) to build a [`HashMap`](std::collections::HashMap), we got an error.
InvalidKey,
InvalidKey {
key: CowStr<'static>,
type_name: &'static str,
},

/// While parsing a datetime, we got an error
InvalidDateTimeValue,
Expand Down Expand Up @@ -111,8 +114,12 @@ impl std::fmt::Display for MerdeError {
MerdeError::MissingValue => {
write!(f, "Missing value")
}
MerdeError::InvalidKey => {
write!(f, "Invalid key")
MerdeError::InvalidKey { key, type_name } => {
write!(
f,
"Invalid key: couldn't convert {:?} to type {}",
key, type_name
)
}
MerdeError::InvalidDateTimeValue => {
write!(f, "Invalid date/time value")
Expand Down

0 comments on commit 95408e4

Please sign in to comment.