Skip to content

Commit

Permalink
feat: add try_get_deserialized (#2042)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattsse authored Feb 11, 2025
1 parent 5708d79 commit f998860
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion crates/serde/src/other/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Support for capturing other fields.
use alloc::{collections::BTreeMap, string::String};
use alloc::{collections::BTreeMap, format, string::String};
use core::{
fmt,
ops::{Deref, DerefMut},
Expand Down Expand Up @@ -75,6 +75,18 @@ impl OtherFields {
self.get_with(key, serde_json::from_value)
}

/// Returns the deserialized value of the field.
///
/// Returns an error if the field is missing
pub fn try_get_deserialized<V: DeserializeOwned>(
&self,
key: impl AsRef<str>,
) -> serde_json::Result<V> {
let key = key.as_ref();
self.get_deserialized(key)
.ok_or_else(|| serde::de::Error::custom(format!("Missing field `{}`", key)))?
}

/// Removes the deserialized value of the field, if it exists
///
/// **Note:** this will also remove the value if deserializing it resulted in an error
Expand Down

0 comments on commit f998860

Please sign in to comment.