我有以下连接到Mongo的功能。为了测试,我关闭mongod,并希望程序继续w / 0 mongo,如果它不可用。如果服务器无法连接,MGO似乎会引发恐慌,所以我在下面写了一个延迟/恢复,但是恐慌仍然导致程序退出。从中恢复的正确方法是什么?
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
}
答案 0 :(得分:4)
运行以下版本的已发布代码。 尽量不要修改代码,至少不要改变行号的位置。这样,如果您发布堆栈跟踪,则数字将匹配。
package main
import (
"fmt"
"time"
)
import (
"labix.org/v2/mgo"
)
func connectToMongo() bool {
ret := false
fmt.Println("enter main - connecting to mongo")
// tried doing this - doesn't work as intended
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")
ret = true
}
} else { // never gets here
fmt.Println("Unable to connect to local mongo instance!")
}
return ret
}
func main() {
if ( connectToMongo() ) {
fmt.Println("Connected")
} else {
fmt.Println("Not Connected")
}
}
当MongoDB启动时,我看到:
enter main - connecting to mongo
Got a collection object
Connected
当MongoDB关闭时,我看到:
enter main - connecting to mongo
Unable to connect to local mongo instance!
Not Connected
如果您没有看到相同的行为,请发布输出,包括您看到的恐慌。