dso15221 2018-10-05 13:55
浏览 614
已采纳

在Golang中处理多个错误的最佳做法

I am writing some code that parses a YAML file and validates the data inside. Each parser returns an error if the value found does not meet the requirements. Right now I am creating an array of errors and setting the return of each call to a different index in the array. My current implementation is working, but it seems wrong and I want to see if there is a better way to accomplish this.

Here is an example

func createStruct(yamlMap map[interface{}]interface{}) (myStruct, error) {
    errs := make([]error, 6)
    s := myStruct{}

    s.Name, errs[0] = getString(yamlMap, "name", true)
    s.Tag, errs[1] = getIntValidRange(yamlMap, "tag", 1, 4094, true)
    s.TaggedPorts, errs[2] = getStringPortList(yamlMap, "tagged_ports", true)
    s.UntaggedPorts, errs[3] = getStringPortList(yamlMap, "untagged_ports", true)
    s.IP, errs[4] = getIPString(yamlMap, "ip", true)
    s.Netmask, errs[5] = getIPString(yamlMap, "netmask", true)

    return s, structCreateErrorChecker(errs)
}

The reason I don't handle each error after each function, is because I want to try to parse everything first and then collect all errors and log them. That is what structCreateErrorChecker() does.

Here is the YAML I am trying to parse (it's come up in the comments). When I say dynamic I mean that there can be any number of these controlling_bridge sections and each vlan section can have any number of vlans.

controlling_bridge_1:
    ip:    "1.1.1.1"
    ports: ["1","2"]
    vlans:
        vlan01:
            name:  "vlan1"
            tag:   1001
            ports: ["1"]
            ip:    "2.2.2.2"
        vlan02:
            name:  "vlan02"
            tag:   1002
            ports: ["3", "4"]
            ip:    "3.3.3.1"

controlling_bridge_2:
    ip:    "1.1.1.1"
    ports: ["1","2"]
    vlans:
        vlan01:
            name:  "vlan1"
            tag:   1001
            ports: ["1"]
            ip:    "2.2.2.2"
        vlan02:
            name:  "vlan02"
            tag:   1002
            ports: ["3", "4"]
            ip:    "3.3.3.1"
  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 Maya的Fbx模型导入Ue4.24后为什么个别部位的UV发生了改变?
      • ¥15 网页设计与开发html
      • ¥15 bin格式的程序文件烧录GD32F105芯片。起始地址填多少?
      • ¥15 python对txt文件的处理
      • ¥25 需要一个能在H5中实现扫码的插件
      • ¥50 ArcGIS或MATLAB实现批量计算整个tif图像的EVI
      • ¥20 两个板子之间CAN通信ID号怎么设置
      • ¥15 两个板子CAN通信的话ID号怎么设置
      • ¥15 vue使用element-ui的el-upload上传图片至服务器,服务端使用的是node.js,图片上传成功,但界面显示不出来,是跨域问题?
      • ¥15 ANSYS APDL循环结果输出