Golang错误合并

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

Golang combining errors

问题

假设你有一个简单的函数,如下所示:

func create(path string) error {
    if err := ioutil.WriteFile(path, []byte{}, 0666); err != nil {
        return err
    }

    if err := os.Chmod(path, 0666); err != nil {
        _ = os.Remove(path)
        return err
    }

    return nil
}

我不喜欢忽略Remove()函数的错误。但我也不想淹没Chmod()函数的错误,也不想保留文件,因为我们没有成功创建它。

这只是一个简单的例子,也许可以以不同的方式编写该函数来避免这种情况,但在更复杂的情况下,可能会遇到这种错误组合。我还没有在Go语言社区中看到这种惯用法,所以有什么惯用的做法吗?

英文:

Lets say you have a simple function as so:

func create(path string) error {
        if err := ioutil.WriteFile(path, []byte{}, 0666); err != nil {
                return err
        }

        if err := os.Chmod(path, 0666); err != nil {
                _ = os.Remove(path)
                return err
        }

        return nil
}

I don't like ignoring the error out of Remove(). But I also don't want to swamp the error out of Chmod() and I don't want to leave the file since we didn't create() it successfully.

This is a simple example, and perhaps the function could be written differently to avoid this, but there are more complex situations that come up and this combining of errors I haven't seen mentioned in the golang community, so whats the idiom?

答案1

得分: 19

解决方案是将Remove的错误存储在一个单独的变量中,并与fmt.Errorf组合起来:

if err := os.Chmod(path, 0666); err != nil {
    if e2 := os.Remove(path); e2 != nil {
        return fmt.Errorf("更改权限时出错(%v);删除文件时出错(%v)", err, e2)
    }
    return err
}
英文:

The solution would be to store the error from Remove in a separate variable, and combine them with fmt.Errorf:

if err := os.Chmod(path, 0666); err != nil {
        if e2 := os.Remove(path); e2 != nil {
            return fmt.Errorf("error changing permissions (%v); error deleting file (%v)", err, e2)
        }
        return err
}

huangapple
  • 本文由 发表于 2014年1月1日 07:51:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/20864359.html
匿名

发表评论

匿名网友

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

确定