2014-01-07 53 views
0

我有以下連接到Mongo的功能。爲了測試,我關閉了mongod,並且希望程序在沒有可用時繼續使用mongo。如果服務器無法連接,MGO似乎會引發恐慌,所以我在下面寫了延遲/恢復,但恐慌仍然導致程序退出。什麼是從這個恢復的正確方法?Golang/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

無法重新創建錯誤。 'mgo.DialWithTimeout'只是返回一個錯誤,'沒有可達的服務器',而不是panicing。請包括'mgo'(版本)的導入路徑和恐慌消息(哪一行發生混亂) – ANisus

+0

請記住,「如果延遲函數具有任何返回值,則在函數完成時它們將被丟棄。」如果您想修改/提供返回值,您將需要使用如下所述的命名返回值:「...如果延遲函數是一個函數文字,並且周圍函數已命名範圍在文字中的結果參數,延遲函數可能會在返回之前訪問並修改結果參數。「 –

回答

3

運行以下版本的發佈代碼。 儘量不要修改代碼,至少不要改變行號的位置。這樣,如果您發佈堆棧跟蹤,這些數字將匹配。

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 

如果你沒有看到相同的行爲,後輸出,包括你看到的恐慌。

+0

我的壞 - 謝謝你的幫助 - 骨頭新手擰緊! – user2644113