`Exit(1)`和返回错误应该在哪里处理?

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

Where to `Exit(1)` and where to return error?

问题

处理程序中深层次错误的惯用方式是什么?如果我在一个包的深处有这样的代码片段:

file, err := os.Open(path)
if err != nil {            
    os.Exit(1) // 或者返回 errors.New("The path is invalid.")
}                          

我应该返回一个错误并通过多个层级的 if {} else {} 块将其传递到 main 函数中,然后在 main 函数中使用 Exit,还是应该立即使用 Exit

使用立即的 Exit 代码看起来更清晰、更易读。但有时很难进行测试。使用返回和检查的代码看起来更糟糕(在我看来),但更容易进行测试并达到100%的覆盖率。

还有一个问题...如果我正在编写一个包,并且它没有 main 函数,我应该将 Exit 留给“用户”程序,并只返回错误吗?

英文:

What is the idiomatic way to handle errors occurred deep in a program layers? If I have such a snippet somewhere deep inside a package:

file, err := os.Open(path)
if err != nil {            
    os.Exit(1) // or return errors.New("The path is invalid.")
}                          

Should I return an error and possibly drag it through a several layers with if {} else {} blocks up to main and Exit in main or Exit immediately?

With immediate Exit code looks cleaner and more readable. But sometimes it is difficult to test. With returns and checks code looks worse (at my opinion) but it is easier to test and reach 100% of coverage.

And one more question... If I'm writing a package and it has no main function should I leave Exits to a "user" program and just return errors?

答案1

得分: 1

基本上,你最好在原地处理错误,而不是将其传递出去。当你需要立即退出时,可以调用os.Exit(),所以也是在原地处理。而且你忘记了另一个选项 - panic()。它会继续执行并评估延迟函数,这允许你进行一些清理工作。在编写包时,不建议调用os.Exit()panic(),以免让用户感到困惑和不可预测。在包中,推荐使用错误的传递方式。

英文:

Basically you better handle error in place not drug it through. You call os.Exit() when you need immediate exit so in place also. And you forget another option - panic(). It goes through and evaluates deferred function which allows you some teardown. While writing a package it's not recommended to call os.Exit() or panic() to not confuse users with unpredictable. In packages promoting errors is the best choice.

huangapple
  • 本文由 发表于 2017年1月29日 00:46:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/41912264.html
匿名

发表评论

匿名网友

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

确定