golang – prevent app from Exiting

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

golang - prevent app from Exiting

问题

在Go语言中,使用panic()可以通过deferrecover()防止应用程序退出并继续执行代码。

然而,我正在尝试在出现dial tcp 192.168.1.1:830: getsockopt: connection refused错误时防止我的应用程序退出。该应用程序会以状态码1退出。从技术上讲,这不是一个错误,所以我无法捕捉到这个错误。我正在使用的外部包在发生这种情况时导致应用程序退出(在这种情况下,是因为端口被阻止)。

那么,我该如何从另一个包中恢复退出并继续我的应用程序呢?以下面的代码为例:

func makeRequest(target string) {
    // 如果连接被拒绝,以状态码1退出
    res, err := request.NewSession(target)
}
英文:

In Go, with a panic() you can use defer and recover() to prevent an app from exiting and continue executing code.

However, I'm trying to prevent my app from exiting when getting a dial tcp 192.168.1.1:830: getsockopt: connection refused. The application Exits with a status code of 1. It's technically not an error so I can't catch the error. The external package I'm using to make the tcp dial causes the app to Exit when this condition occurs. (In this case, it's because the port is blocked.)

So how can I recover the Exit from another package and continue on with my application? Take the below as an example:

func makeRequest(target string) {
    // Exits with status code 1, if connection refused 
    res, err := request.NewSession(target)
}

答案1

得分: 1

很遗憾,你无法从调用os.Exit()中恢复。文档中指出,它会立即退出,甚至不会调用延迟执行的函数。我建议如果一个包中包含退出操作,最好不要使用它,因为这是一个相当糟糕的设计。

英文:

Unfortunately no, you can't recover from a call to os.Exit(). The documentation says that it exits immediately, and not even differed functions are called. I recommend to not use a package if it has an exit in it, as that is a pretty bad design.

huangapple
  • 本文由 发表于 2017年7月21日 02:16:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/45222362.html
匿名

发表评论

匿名网友

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

确定