Devin
Devin

Reputation: 1021

golang - prevent app from Exiting

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)
}

Upvotes: 0

Views: 2762

Answers (1)

Mauricio
Mauricio

Reputation: 439

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.

Upvotes: 1

Related Questions