Skip to content

Commit 107c2d1

Browse files
authored
Merge pull request #1106 from serde-rs/invalidvalue
Handle Unexpected::Unit in Error::invalid_value
2 parents e56cc69 + 62ca3e4 commit 107c2d1

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

src/error.rs

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -438,11 +438,20 @@ impl de::Error for Error {
438438

439439
#[cold]
440440
fn invalid_type(unexp: de::Unexpected, exp: &dyn de::Expected) -> Self {
441-
if let de::Unexpected::Unit = unexp {
442-
Error::custom(format_args!("invalid type: null, expected {}", exp))
443-
} else {
444-
Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp))
445-
}
441+
Error::custom(format_args!(
442+
"invalid type: {}, expected {}",
443+
JsonUnexpected(unexp),
444+
exp,
445+
))
446+
}
447+
448+
#[cold]
449+
fn invalid_value(unexp: de::Unexpected, exp: &dyn de::Expected) -> Self {
450+
Error::custom(format_args!(
451+
"invalid value: {}, expected {}",
452+
JsonUnexpected(unexp),
453+
exp,
454+
))
446455
}
447456
}
448457

@@ -453,6 +462,18 @@ impl ser::Error for Error {
453462
}
454463
}
455464

465+
struct JsonUnexpected<'a>(de::Unexpected<'a>);
466+
467+
impl<'a> Display for JsonUnexpected<'a> {
468+
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
469+
if let de::Unexpected::Unit = self.0 {
470+
formatter.write_str("null")
471+
} else {
472+
Display::fmt(&self.0, formatter)
473+
}
474+
}
475+
}
476+
456477
// Parse our own error message that looks like "{} at line {} column {}" to work
457478
// around erased-serde round-tripping the error through de::Error::custom.
458479
fn make_error(mut msg: String) -> Error {

0 commit comments

Comments
 (0)