Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return an error from `deserialize`?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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`"))
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading