Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 986
porton Avatar asked Oct 24 '25 16:10

porton


1 Answers

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`"))
    }
}
like image 127
cafce25 Avatar answered Oct 27 '25 11:10

cafce25