我有以下连接到 Mongo 的功能。为了测试,我关闭了 mongod,并希望允许程序在不可用的情况下继续 w/0 mongo。好像MGO服务器连接不上的时候会抛出panic,所以我在下面写了一个defer/recover,但是panic还是会导致程序退出。从中恢复的正确方法是什么?
func connectToMongo(sess *mgo.Session, coll *mgo.Collection, sessionErr error) bool {
fmt.Println("enter main - connecting to mongo")
// tried doing this - doesn't work as intended
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok := r.(error)
if !ok {
fmt.Printf("pkg: %v, error: %s", r, err)
}
}
return false
}()
maxWait := time.Duration(5 * time.Second)
sess, sessionErr = mgo.DialWithTimeout("localhost", maxWait)
if sessionErr == nil {
session.SetMode(mgo.Monotonic, true)
coll = session.DB("MyDB").C("MyCollection")
} else { // never gets here
fmt.Println("Unable to connect to local mongo instance!")
}
return true
}