-
I just ran into an issue where I have: #[serde_as(deserialize_as = "OneOrMany<_, PreferOne>")]
pub action: Vec<Action>, and a user tried to set: {
"action": [
[ "Suspend" ]
]
} which is invalid because they are trying to assign an array of arrays of Action instead of just an array of Action. The resulting error message looks like:
line 263 is the end of the input json document. In the interest of trying to improve the error message, I tried to apply I think it would be nice if I could specialize or newtype-wrap that I've tried to apply fn one_or_many<'de, T, D>(deserializer: D, expecting: &'static str) -> Result<Vec<T>, D::Error>
where
T: Deserialize<'de> ,
D: Deserializer<'de>,
{
let result = serde_with::de::DeserializeAsWrap::<
Vec<T>,
OneOrMany<T, PreferOne> // I'm unsure if I need T or Vec<T> here, but neither compile
>::deserialize(deserializer)?; // the intent is to map_err here and do some editorializing with `expecting`
Ok(result.into_inner())
}
fn one_or_many_action<'de, D>(deserializer: D) -> Result<Vec<Action>, D::Error>
where
D: Deserializer<'de>,
{
one_or_many(deserializer, "either a single Action or an array of Action, for field action")
}
#[serde_as]
#[derive(Deserialize, Serialize, Debug, Hash, Clone)]
struct Rule {
#[serde(deserialize_with = "one_or_many_action")]
pub action: Vec<Action>,
} but I think I'm having a similar naming/resolution issue as is mentioned in #649 I'm looking for a suggestion (or ideally, a solution!) for how to achieve an annotated/expanded error message for this sort of situation! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The error message you see is part of the serde_with/serde_with/src/de/impls.rs Lines 1527 to 1557 in aede9d5 I think this matches what you are trying to do in the code snippet. It does not replace the error message of fn one_or_many<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
where
T: Deserialize<'de>,
D: Deserializer<'de>,
{
let result: Result<Vec<T>, _> = OneOrMany::<Same, formats::PreferOne>::deserialize_as(deserializer);
match result {
Ok(r) => Ok(r),
Err(err) => Err(serde::de::Error::custom("My Custom Error Message"))
}
} |
Beta Was this translation helpful? Give feedback.
The error message you see is part of the
DeserializeAs
implementation ofOneOrMany
. As such it is not really possible to change it, as this would require modifying theDeserializeAs
code. In the future maybe it might be possible to refer to a const generic static string, but that is impossible right now too.serde_with/serde_with/src/de/impls.rs
Lines 1527 to 1557 in aede9d5