Home >Backend Development >Golang >How to Recover from 'No Reachable Servers' Panics When Connecting to MongoDB with MGO in Go?

How to Recover from 'No Reachable Servers' Panics When Connecting to MongoDB with MGO in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 08:01:02230browse

How to Recover from

Golang / Mongo: Handling "No Reachable Servers" Panic

Problem:

When attempting to connect to Mongo with MGO in Go, a panic is thrown if the server is unreachable. How can this panic be recovered from to allow the program to continue execution?

Answer:

To handle the panic thrown by MGO when no reachable servers are available, the following code can be used:

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

func connectToMongo() bool {
    // Define a flag to indicate success
    ret := false

    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Detected panic")
        }
    }()

    maxWait := time.Duration(5 * time.Second)
    session, sessionErr := mgo.DialWithTimeout("localhost", 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
}

In this modified version:

  1. The defer statement is moved after the DialWithTimeout call, which ensures that it executes regardless of whether the call succeeds or panics.
  2. Inside the defer function, the recover() function is used to catch the panic. This ensures that the program does not exit due to the panic.
  3. The fmt.Println("Detected panic") statement is added to indicate that a panic was detected.
  4. The var ok bool and err, ok := r.(error) are removed as they are unnecessary for this scenario.

By incorporating these changes, the program can handle the panic caused by MGO's inability to connect to Mongo and continue execution without exiting.

The above is the detailed content of How to Recover from 'No Reachable Servers' Panics When Connecting to MongoDB with MGO in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn