2

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.

porton
  • 5,214
  • 11
  • 47
  • 95

1 Answers1

4

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`"))
    }
}
cafce25
  • 15,907
  • 4
  • 25
  • 31