mongodb - Golang/MGO—— panic : no reachable servers

标签 mongodb go mgo

我有以下连接到 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
}

最佳答案

运行您发布的代码的以下版本。 尽量不要修改代码,至少不要改变行号的位置。这样,如果您发布堆栈跟踪,数字就会匹配。

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

如果您没有看到相同的行为,请发布输出,包括您看到的 panic 。

关于mongodb - Golang/MGO—— panic : no reachable servers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20976030/

相关文章:

go - 修复 go 使用的工具版本

mongodb - 具有嵌套嵌入文档和 $project 的 Mongo 聚合管道 $lookup

mongodb - 如何使用 MongoDB 和 C# 驱动程序查询子文档集合

javascript - 替换数组字段值

http - ResponseWriter.Write 返回的 int 是什么意思?

list - 为什么 `list.Remove()` 试图明确避免内存泄漏?

mongodb - 在文档 mongodb mgo 驱动程序中增加嵌套数组的特定值

mongodb - 可选在 .Find() MongoDB 查询中查找

javascript - 在原子操作中测试和递减?

java - 使用 Spring Mongo (java) 映射聚合中的字段