正确处理错误

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

Properly handling errors

问题

通常在Go语言中,你会发现以下的约定:

res, err := thingThatCanError(arg)

if err != nil {
    // 处理错误
}

然而,很明显,对于大量这样的调用,这种方式会变得非常混乱:

res, err := thingThatCanError(arg)

if err != nil {
    // 处理错误
}

res, err2 := thingThatCanError(arg)

if err2 != nil {
    // 处理错误
}

res, err3 := thingThatCanError(arg)

if err3 != nil {
    // 处理错误
}

这里有比实际代码更多的样板错误处理代码!这个网站建议我们避免这种情况,但没有给出如何清理这种代码的示例。Go博客提供了一个有用的示例,展示了如何使用一个有意义的错误处理程序来清理一个同质的HTTP应用程序。

但是,想象一下,如果每个调用都不是同质的,也就是说没有相同的"中心思想",那么一个单一的"错误处理程序结构"可能就没有太多意义了。

是否有一种方法可以清理这种类型的代码呢,即那些在错误方面不太"协调"的函数呢?

英文:

Typically in Go you find the following convention:

res, err := thingThatCanError(arg)

if err != nil {
        // handle it
}

However, it's obvious this gets VERY unruly very quickly for a large number of these calls:

res, err := thingThatCanError(arg)

if err != nil {
        // handle it
}

res, err2 := thingThatCanError(arg)

if err2 != nil {
        // handle it
}

res, err3 := thingThatCanError(arg)

if err3 != nil {
        // handle it
}

There's more lines of boilerplate error handling than code! This website says to avoid this but does not give an example on how to clean up this smell. A useful example comes straight from the Go blog that shows us how to clean up a homogenous HTTP app with an error handler that makes sense.

But imagine each of these calls aren't homogenous, as in with the same "central idea", so a single "error handler struct" wouldn't make a lot of sense.

Is there a way to clean up this type of code smell with functions that don't "mesh together" nicely in terms of errors?

答案1

得分: 1

很遗憾,有时候无法避免这些模式。你可以使用 panic/defer 作为临时的 try/catch 系统,但是社区不太推荐这样做。

在 Go 中,if 语句可以与赋值结合使用,所以

err := thing.Do()
if err != nil {
   return err
}

可以简化为

if err := thing.Do(); err != nil {
   return err
}
英文:

Unfortunately there's sometimes no way around these patterns. You could use panic/defer as a makeshift try/catch system but the community looks down upon it.

If statements in Go can be combined with assignments so

err := thing.Do()
if err != nil {
   return err
}

can become

if err := thing.Do(); err != nil {
   return err
}

huangapple
  • 本文由 发表于 2017年3月16日 05:08:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/42820702.html
匿名

发表评论

匿名网友

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

确定