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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程