vanarajcs
vanarajcs

Reputation: 978

Golang error handling

package main

import "time"

func main() {
    // infinite loop
    for {

        for i := 0; i < 2; i++ {

            conn, err := opentsdb.OpenConnection()

            if err {
                time.Sleep(10 * time.Second)
            }

        }
    }
}

I need Program will execute from the beginning if an error block occur.

How to handle it?

Upvotes: 0

Views: 803

Answers (1)

JimB
JimB

Reputation: 109318

Using goto is a common way to handle error flows in a nested loop

func main() {
RESTART:
    for {
        for i := 0; i < 2; i++ {
            conn, err := opentsdb.OpenConnection()
            if err {
                time.Sleep(10 * time.Second)
                goto RESTART
            }
        }
    }
}

If you only want to restart the outer loop, and there's nothing between the RESTART label and the for loop, you can use continue RESTART to continue the loop at the RESTART label. In this simple case, just using break will continue the outer loop as well.

Upvotes: 7

Related Questions