doupian9490 2018-09-28 19:49
浏览 38
已采纳

从函数和调用者到终端的Golang错误处理

I want to ask about best practise of error handling, Lets assume I've the following function that read file parse it, which could return two types of errors , when the file not found and the unmarshal failed

func Parse(source string) (bma.Bma, error) {
    file, err := ioutil.ReadFile(source + "bma.yaml")
    m := bma.Bma{}
    if err != nil {
        logs.Error("Not able to read the bma file")
        return m, err
    }
    err = yaml.Unmarshal([]byte(file), &m)
    if err != nil {
        logs.Error("Not able to unmarshal the bma file ")
        return m, err
    }
    return m, err
}

Now If I call to this function and there is error I printing also this error, the Program is CLI program so I think there is too much error will be printed if case of issue, Is It OK, or there is better approach ?

bma ,err := Parse("path")
    if err != nil {
        logs.Error("Error while parsing ")
        return m, err
    }
  • 写回答

2条回答 默认 最新

  • dongwu5318 2018-09-28 20:37
    关注

    I think what you are asking is more about when to print errors not when handle or not the errors. In my case I like printing all logs that I can if I think they will be useful for me in future.

    In your case maybe the message logs.Error("Error while parsing ") is too verbose because you are not showing any details there.

    Other approach that you can consider is returning your custom error to the top level functions instead of in the deeper ones and only display the log message there. In the case of the example should be something like this:

    func main() {
        bma, err := Parse("path")
        if err != nil {
            log.Println(err)
            return
        }
    }
    
    func Parse(source string) (bma.Bma, error) {
        file, err := ioutil.ReadFile(source + "bma.yaml")
        m := bma.Bma{}
        if err != nil {
            return m, fmt.Errorf("Not able to read the bma file: %s", err.Error())
        }
        err = yaml.Unmarshal([]byte(file), &m)
        if err != nil {
            return m, fmt.Errorf("Not able to unmarshal the bma file: %s", err.Error())
        }
        return m, err
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?