英文:
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`"))
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论