Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle Unexpected::Unit in Error::invalid_value #1106

Merged
merged 2 commits into from
Jan 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 26 additions & 5 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,11 +438,20 @@ impl de::Error for Error {

#[cold]
fn invalid_type(unexp: de::Unexpected, exp: &dyn de::Expected) -> Self {
if let de::Unexpected::Unit = unexp {
Error::custom(format_args!("invalid type: null, expected {}", exp))
} else {
Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp))
}
Error::custom(format_args!(
"invalid type: {}, expected {}",
JsonUnexpected(unexp),
exp,
))
}

#[cold]
fn invalid_value(unexp: de::Unexpected, exp: &dyn de::Expected) -> Self {
Error::custom(format_args!(
"invalid value: {}, expected {}",
JsonUnexpected(unexp),
exp,
))
}
}

Expand All @@ -453,6 +462,18 @@ impl ser::Error for Error {
}
}

struct JsonUnexpected<'a>(de::Unexpected<'a>);

impl<'a> Display for JsonUnexpected<'a> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
if let de::Unexpected::Unit = self.0 {
formatter.write_str("null")
} else {
Display::fmt(&self.0, formatter)
}
}
}

// Parse our own error message that looks like "{} at line {} column {}" to work
// around erased-serde round-tripping the error through de::Error::custom.
fn make_error(mut msg: String) -> Error {
Expand Down