How to return an error from `deserialize`?

Advertisements

When implementing Deserialize, how to return an error?

impl<'de> Deserialize<'de> for Response {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
        ... // Which error to return here?
    }
}

Here every error must be convertible to D::Error, but D::Error maybe any whatsoever type. So, I cannot create a type convertible to D::Error.

How to deal with this situation? I am almost sure there is some way to create a deserializer that can return an error, but I don’t know how.

>Solution :

Since D::Error is required to implement serde::de::Error you can just use Error::custom or any of it’s more specific constructors:

impl<'de> Deserialize<'de> for Response {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
        Err(<D::Error as serde::de::Error>::custom("your type imlementing `Display`"))
    }
}

Leave a Reply Cancel reply