Go错误返回模式的名称是什么?

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

What is the name of Go error return pattern?

问题

Go语言不支持try-catch,而是采用返回错误值的方式来处理错误。如果发生错误,错误值将被设置为实现了error接口的类型,否则将被设置为nil

这种错误处理模式的名称是什么?

英文:

Go doesn't support try-catch, Instead Go coding style for error handling is to return an error along side the potential valid value. If an error accord the error will be set with implementation of the error interface, otherwise it will be set to nil.

See the flowing signature:

func Open(name string) (file *File, err error)

I would like to know what is the name of this "error handling" pattern.

答案1

得分: 5

我认为你在寻找的是文献中称为状态返回的东西。Golang只是通过考虑错误(或故障状态)被定义为程序中遇到的不希望和不寻常的条件来实现它。

与此同时,在2003年(比Golang发布前六年)Ned Batchelder写了一篇关于异常与状态返回的好处(这种情况下主要是针对C++)的文章,指出了一些优点,如更清晰的代码。Joel Spolsky也表达了他的观点,但在这种情况下,他更支持状态返回而不是异常。

在Go创建之后的2014年,Martin Fowler也写了一篇关于以通知形式返回错误而不是抛出异常的文章

英文:

I think that what you're looking for is named status return in the literature. Golang just implements it by the consideration an error (or faulty status) is defined as the unwanted and unusual conditions encountered in the program.

Meanwhile already in 2003 (six years before Golang was launched) Ned Batchelder wrote about the benefits of Exceptions vs Status Returns (in this case focused on C++) by pointing out some benefits as cleaner code, Joel Spolsky also showed his point of view, but in this case in favour of the status' return opposed to Exceptions.

Way after the creation of Go, in 2014, Martin Fowler also wrote about returning errors in form of Notifications instead of throwing Exceptions.

huangapple
  • 本文由 发表于 2022年4月4日 19:31:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/71736540.html
匿名

发表评论

匿名网友

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

确定