英文:
Error returned from custom json Umarshaller lacks context
问题
我正在编写一个解析JSON对象的函数。我想要生成结构化的错误消息,指示哪些具体字段存在错误。
最初,我检查错误类型是否为*json.UnmarshalTypeError
,然后从其Field
属性中获取JSON标签名称。不幸的是,如果我将JSON解组到的结构体具有实现自己的UnmarshalJSON
函数的自定义类型,这种方法会失败。它们返回的错误是我的自定义错误,无法确定它们来自结构体的哪个字段。
对比内置错误和自定义错误的示例:https://play.golang.org/p/auH3PE7j5H
目前,我正在考虑改用反射,最初将对象解组为json.RawMessage
的映射,然后逐个解组字段,以便我可以识别出有问题的字段。是否有更简单的方法?这将要求我基本上复制内部的json包逻辑,以分析JSON标签,以确定将每个原始消息解组到哪个字段。
英文:
I am writing a function that parses a JSON object. I would like to emit structured error messages that indicate which specific fields have errors in them.
Originally I checked if the error type was *json.UnmarshalTypeError
and then retrieved the json tag name from its Field
property. Unfortunately this fails if the struct to which I'm unmarshalling the JSON has custom types that implement their own UnmarshalJSON
functions. The errors they return are my custom errors and there is no way to determine which field from the struct they came from.
Playground contrasting the built in vs custom error: https://play.golang.org/p/auH3PE7j5H
At this point I'm considering changing to using reflection, unmarshalling the object into a map of json.RawMessage
initially and then unmarshalling one field at a time so that I can identify the problematic field(s). Is there any simpler way? This will require me to basically duplicate the internal json package logic to analyze the json tags to figure out which field to unmarshal each raw message into.
答案1
得分: 2
json.UnmarshalTypeError
被导出,它的所有字段也被导出。你可以从自定义的编组器中返回这个错误类型,没有任何问题。事实上,我敢说这是这个类型的一个_预期用法_!
func (third *Second) UnmarshalJSON(data []byte) error {
return &json.UnmarshalTypeError{
// ...
}
}
英文:
json.UnmarshalTypeError
is exported, as are all of its fields. There's no reason you can't return this error type from your custom marshalers. In fact, I'd venture this is an intended use of this type!
func (third *Second) UnmarshalJSON(data []byte) error {
return &json.UnmarshalTypeError{
// ...
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论