从自定义 JSON 解码器返回的错误缺少上下文。

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

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{
        // ...
    }
}

huangapple
  • 本文由 发表于 2017年4月6日 05:32:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/43242001.html
匿名

发表评论

匿名网友

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

确定