将所有错误处理中的 golang 错误代码替换为 panic。

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

Replacing golang error codes with panic for all error handling

问题

我们有一个用Go语言编写的中等规模应用程序。在所有的代码行中,大约60%用于错误处理。就像这样:

if err != nil {
   return err
}

随着时间的推移,一遍又一遍地编写这些代码变得很烦人,我们现在正在考虑用panic替换所有的错误代码。

我知道panic并不是用来这样使用的。

有什么潜在的陷阱,有没有人有类似的经验?

英文:

We have medium sized application written in go. From all the code lines about 60 percent goes to code error handling. Something like this:

if err != nil {
   return err
}

After some time, writing this lines over and over again becomes tiresome and we are now thinking to replace all error codes with panics.

I know panics aren't meant to be used like that.

What can be potential pitfall and does anyone have experience with something similar ?

答案1

得分: 1

主要的陷阱是广泛使用锤子来拧螺丝。恐慌是指无法恢复/意外错误,错误返回值是指可恢复/预期错误。

将“恐慌”一词替换为“崩溃”,因为从概念上讲,这就是恐慌的含义。你真的想要编写一个设计上在任何事情出现任何微小问题时都会崩溃的应用程序吗?那将是地球上最脆弱的应用程序,完全违背了容错性的原则。

英文:

The main pitfall would be a widespread use of hammers to drive screws. Panic is for unrecoverable/unexpected errors, error return values are for recoverable/expected errors.

Replace the word "panic" with "crash", because that is conceptually what a panic is. Do you honestly want to write an application that by design crashes whenever anything goes in any way remotely wrong? That would be the most fragile application on Earth, the very antithesis of fault tolerance.

答案2

得分: 0

正如所有评论所建议的,你可能正在签署一场灾难,让我补充一下,无论是谁来维护这段代码,当事情出错时,他们都会疯狂地试图弄清楚到底出了什么问题,如果你不进行适当的错误处理(即使那个人是你自己,它也会困扰着你)。

只是重复其他人所说的问题 - 无法区分这两种情况:

  • 可预测且可能可恢复的条件
  • 可能是无法恢复的情况(需要退出应用程序或在更高级别处理 - 这可能来自你自己应用程序的条件或某个第三方库,但它迫使你退出正常的执行路径)

恐慌是为后一种类型保留的。

英文:

As all the comments suggest you could be signing up for a disaster and let me add, whosoever is going to maintain this code will go insane trying to figure out what exactly went wrong when things do go awry if you don't do proper error handling (even if that person is you, it's going to haunt you).

Just repeating what others have said - the problem is being unable to differentiate between these two

  • a predictable & possibly recoverable condition
  • perhaps what is unrecoverable (need to exit the application or be handled at a higher level - this may be coming from your own application's conditions or some third party library, but is forcing you out of your normal execution path)

Panics are reserved for the latter types.

huangapple
  • 本文由 发表于 2017年3月9日 23:31:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/42699313.html
匿名

发表评论

匿名网友

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

确定