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