Golang / MGO — 报错:没有可达的服务器

huangapple go评论88阅读模式
英文:

Golang / MGO -- panic: no reachable servers

问题

我有以下连接到Mongo的函数。为了测试,我关闭了mongod,并希望在没有Mongo可用时允许程序继续运行。似乎如果无法连接到服务器,MGO会引发panic,所以我写了一个defer/recover,但panic仍然导致程序退出。从这种情况中恢复的正确方法是什么?

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 {
            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 { // 永远不会执行到这里
        fmt.Println("无法连接到本地Mongo实例!")
    }
    return true
}
英文:

I have the following function that connects to Mongo. For testing, I shutdown mongod, and want to allow the program to continue w/0 mongo if it's not available. It seems that MGO throws a panic if the server can't be connected, so I wrote a defer/recover below, but the panic still causes the program to exit. What's the proper way to recover from this?

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
}

答案1

得分: 4

请运行以下版本的代码:

package main

import (
	"fmt"
	"time"
)

import (
	"labix.org/v2/mgo"
)

func connectToMongo() bool {
	ret := false
	fmt.Println("进入主函数 - 连接到MongoDB")

	// 尝试这样做 - 不按预期工作
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("检测到恐慌")
			var ok bool
			err, ok := r.(error)
			if !ok {
				fmt.Printf("pkg: %v, 错误: %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("获得一个集合对象")
			ret = true
		}
	} else { // 永远不会执行到这里
		fmt.Println("无法连接到本地MongoDB实例!")
	}
	return ret
}

func main() {
	if connectToMongo() {
		fmt.Println("已连接")
	} else {
		fmt.Println("未连接")
	}
}

当MongoDB运行时,你会看到:

进入主函数 - 连接到MongoDB
获得一个集合对象
已连接

当MongoDB关闭时,你会看到:

进入主函数 - 连接到MongoDB
无法连接到本地MongoDB实例!
未连接

如果你没有看到相同的行为,请发布输出,包括你看到的恐慌信息。

英文:

Run the following version of your posted code.
Try to not modify the code, at least not changing the position of the line numbers. That way, if you post a stacktrace, the numbers will match.

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")
    }
}

When MongoDB is up, I see:

enter main - connecting to mongo
Got a collection object
Connected

When MongoDB is down, I see:

enter main - connecting to mongo
Unable to connect to local mongo instance!
Not Connected

If you don't see the same behavior, post the output, including the panic you see.

huangapple
  • 本文由 发表于 2014年1月7日 23:52:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/20976030.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定