如何从 `deserialize` 返回错误?

huangapple go评论62阅读模式
英文:

How to return an error from `deserialize`?

问题

在实现Deserialize时,如何返回错误?

impl<'de> Deserialize<'de> for Response {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
        ... // 在这里返回哪种错误?
    }
}

这里每个错误都必须能够转换为D::Error,但D::Error可以是任何类型。因此,我无法创建一个可转换为D::Error的类型。

如何处理这种情况?我几乎确定有一种方法可以创建一个可以返回错误的反序列化器,但我不知道该如何做。

英文:

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.

答案1

得分: 4

由于 D::Error 需要实现 serde::de::Error,您可以直接使用 Error::custom 或其更具体的构造函数之一:

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 implementing `Display`"))
    }
}
英文:

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

huangapple
  • 本文由 发表于 2023年2月24日 08:20:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551575.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定