退出时出现错误代码? [英] Exit with error code in go?

查看:134
本文介绍了退出时出现错误代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



退出的文档说明程序立即终止,延迟功能不运行。和log.Fatal只是调用Exit。对于不是令人发指的错误,终止程序而不运行延迟的功能似乎是极端的。



我应该传递一些状态,表示出现错误,然后在某个点我知道我可以安全地退出所有延迟的函数已经运行了,然后调用Exit(1)?

解决方案

p>我在大多数真正的主要包中按照这些方式做了一些事情,所以采用 return err 约定尽快,并且正确终止:

  func main(){
if err:= run ); err!= nil {
fmt.Fprintf(os.Stderr,error:%v\\\
,err)
os.Exit(1)
}
}

func run()error {
err:= something()
if err!= nil {
return err
}
// etc
}


What's the idiomatic way to exit a program with some error code?

The documentation for Exit says "The program terminates immediately; deferred functions are not run.", and log.Fatal just calls Exit. For things that aren't heinous errors, terminating the program without running deferred functions seems extreme.

Am I supposed to pass around some state that indicate that there's been an error, and then call Exit(1) at some point where I know that I can exit safely, with all deferred functions having been run?

解决方案

I do something along these lines in most of my real main packages, so that the return err convention is adopted as soon as possible, and has a proper termination:

func main() {
    if err := run(); err != nil {
        fmt.Fprintf(os.Stderr, "error: %v\n", err)
        os.Exit(1)
    }
}

func run() error {
    err := something()
    if err != nil {
        return err
    }
    // etc
}

这篇关于退出时出现错误代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆