Convention for wrapping errors in Golang

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

Convention for wrapping errors in Golang

问题

在golang中包装错误时,创建新错误时应该在开头还是结尾使用%w占位符?或者这并不重要,因为没有约定或建议 - 我们可以使用任何使错误字符串更容易理解的方式?

%w在结尾使用时的示例:

if err != nil {
    return fmt.Errorf("decompress %v: %w", name, err)
}

%w在开头使用时的示例:

if record.BoatSize != 0 {
    err = fmt.Errorf("%w: boatSize is set", ErrInvalidBoatRecord)
}
英文:

When wrapping errors in golang, should the %w verb be used at the beginning or at the end when creating the new error? Or it doesn't matter because there's no convention or recommendation - we can use whatever makes the error string easier to understand?

Eaxample when %w is used at the end:

if err != nil {
    return fmt.Errorf("decompress %v: %w", name, err)
}

And an example when %w is used at the beginning:

if record.BoatSize != 0 {
	err = fmt.Errorf("%w: boatSize is set", ErrInvalidBoatRecord)
}

答案1

得分: 3

%w的位置在包装错误时和解包错误时都没有被使用,所以它并不重要。

使用哪种方式取决于哪种方式能使你的错误消息更清晰。

通常将其添加到末尾更为常见,当错误链接时,从一般错误到更具体错误时,读起来更好。例如:

IO错误:文件打开错误:文件不存在:example.txt

英文:

The position of %w is not used when wrapping , nor when unwrapping the error, so it does not matter.

Use whichever makes your error message clearer.

Usually adding it to the end is more common, it reads well when chaining the errors, going from general to more specific errors. For example:

> IO error: file open error: file does not exist: example.txt

huangapple
  • 本文由 发表于 2022年8月2日 23:29:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/73210117.html
匿名

发表评论

匿名网友

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

确定