Golang / Mongo: Handling "No Reachable Servers" Panic
Problem:
When attempting to connect to Mongo with MGO in Go, a panic is thrown if the server is unreachable. How can this panic be recovered from to allow the program to continue execution?
Answer:
To handle the panic thrown by MGO when no reachable servers are available, the following code can be used:
import ( "labix.org/v2/mgo" ) func connectToMongo() bool { // Define a flag to indicate success ret := false defer func() { if r := recover(); r != nil { fmt.Println("Detected panic") } }() maxWait := time.Duration(5 * time.Second) session, sessionErr := mgo.DialWithTimeout("localhost", maxWait) if sessionErr == nil { session.SetMode(mgo.Monotonic, true) coll := session.DB("MyDB").C("MyCollection") if coll != nil { fmt.Println("Got a collection object") ret = true } } else { // never gets here fmt.Println("Unable to connect to local mongo instance!") } return ret }
In this modified version:
By incorporating these changes, the program can handle the panic caused by MGO's inability to connect to Mongo and continue execution without exiting.
The above is the detailed content of How to Recover from 'No Reachable Servers' Panics When Connecting to MongoDB with MGO in Go?. For more information, please follow other related articles on the PHP Chinese website!