Home >Backend Development >Golang >How to Gracefully Recover from MongoDB Connection Failures in Go with MGO?
Recovering from MongoDB Connection Failure in Go with MGO
In Go, the MGO package is used to interact with MongoDB. However, connecting to MongoDB can sometimes fail, causing a panic in the program. This article provides a solution to gracefully recover from such connection failures.
The following function attempts to connect to MongoDB and return a session and collection if successful:
func connectToMongo(sess *mgo.Session, coll *mgo.Collection, sessionErr error) bool { fmt.Println("enter main - connecting to mongo") defer func() { if r := recover(); r != nil { fmt.Println("Detected panic") var ok bool err, ok := r.(error) if !ok { fmt.Printf("pkg: %v, error: %s", r, err) } } }() maxWait := time.Duration(5 * time.Second) session, sessionErr = mgo.DialWithTimeout("localhost:27017", maxWait) if sessionErr == nil { session.SetMode(mgo.Monotonic, true) coll = session.DB("MyDB").C("MyCollection") if coll != nil { fmt.Println("Got a collection object") return true } } else { // never gets here fmt.Println("Unable to connect to local mongo instance!") } return false }
The problem with the original code is that the panic interrupt the program before the defer function can execute. To fix this, the recover() function should be called inside the defer statement, after the connection attempt.
The modified code:
var mongoUp bool func init() { if ( connectToMongo() ) { mongoUp := true fmt.Println("Connected") } else { mongoUp = false fmt.Println("Not Connected") } }
When MongoDB is running, the program successfully connects and sets mongoUp to true. When MongoDB is not running, the program logs the failure and sets mongoUp to false.
This solution allows the program to gracefully handle MongoDB connection failures and continue execution without crashing.
The above is the detailed content of How to Gracefully Recover from MongoDB Connection Failures in Go with MGO?. For more information, please follow other related articles on the PHP Chinese website!