Skip to content

Commit 115dcb1

Browse files
committed
Add support for preserving parts of custom error messages
1 parent 87794c2 commit 115dcb1

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

src/de/mod.rs

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ pub enum Error {
6868
TrailingComma,
6969

7070
/// Error with a custom message that we had to discard.
71-
CustomError,
71+
CustomError(heapless::String<heapless::consts::U64>),
7272

7373
#[doc(hidden)]
7474
__Extensible,
@@ -611,17 +611,17 @@ impl<'a, 'de> de::Deserializer<'de> for &'a mut Deserializer<'de> {
611611
}
612612

613613
impl de::Error for Error {
614-
// We can’t alloc a String to save the msg in, so we have this less-than-useful
615-
// error as better than panicking with unreachable!. These errors can arise from
616-
// derive, such as "not enough elements in a tuple" and "missing required field".
617-
//
618-
// TODO: consider using a heapless::String to save the first n characters of this
619-
// message.
620-
fn custom<T>(_msg: T) -> Self
614+
fn custom<T>(msg: T) -> Self
621615
where
622616
T: fmt::Display,
623617
{
624-
Error::CustomError
618+
use core::fmt::Write;
619+
620+
let mut string = heapless::String::new();
621+
// Intentionally discard the result here, which ignores overflow and lets us keep the first
622+
// N error message characters
623+
let _ = write!(string, "{}", msg);
624+
Error::CustomError(string)
625625
}
626626
}
627627

@@ -661,7 +661,7 @@ impl fmt::Display for Error {
661661
value."
662662
}
663663
Error::TrailingComma => "JSON has a comma after the last value in an array or map.",
664-
Error::CustomError => "JSON does not match deserializer’s expected format.",
664+
Error::CustomError(msg) => msg.as_str(),
665665
_ => "Invalid JSON",
666666
}
667667
)
@@ -880,7 +880,9 @@ mod tests {
880880
// wrong number of args
881881
assert_eq!(
882882
crate::from_str::<Xy>(r#"[10]"#),
883-
Err(crate::de::Error::CustomError)
883+
Err(crate::de::Error::CustomError(
884+
"invalid length 1, expected tuple struct Xy with 2 elements".into()
885+
))
884886
);
885887
assert_eq!(
886888
crate::from_str::<Xy>(r#"[10, 20, 30]"#),

0 commit comments

Comments
 (0)