英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论