Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat code if an error occured

Tags:

go

I have a code which is doing a very long ETL operation. There are network problems sometimes. I want to catch the error read tcp 10.10.10.10:32423 -> 20.20.20.20:2344: i/o timeout and retry the operation again.

Here is my code:

for {
    err := mssql.Db.ProcessAllData(true, &processedAsutpIds, filename)
    if err == nil {
      fmt.Println("done.")
      os.Exit(0)
    } else {
      fmt.Println(err.Error())
      fmt.Println("!!!! Error occurred - sleep for 5 minutes")
      time.Sleep(time.Minute * 5)
    }
}

Is it possible to rewrite it in more idiomatic way ?

like image 307
ceth Avatar asked Dec 02 '17 10:12

ceth


People also ask

How do you repeat codes at a certain time?

To loop through a set of code a certain number of times, you can use the range() function, which returns a list of numbers starting from 0 to the specified end number. You haven't learned about functions yet, but you will soon!

Is there a repeat code in Python?

The most common way to repeat a specific task or operation N times is by using the for loop in programming. We can iterate the code lines N times using the for loop with the range() function in Python.

How do you repeat a set of codes in Python?

You can create a variable, and then say that as long as the variable is true to its value, to repeat the code in the for loop.


1 Answers

You might consider a retry function such as the one described in "My favorite #golang retry function" by Alexandre Bourget:

    var signedContent []byte
    err := retry(5, 2*time.Second, func() (err error) {
        signedContent, err = signFile(unsignedFile, contents)
        return
    })
    if err != nil {
        log.Println(err)
        http.Error(w, err.Error(), 500)
        return
    }

With the retry function being:

func retry(attempts int, sleep time.Duration, f func() error) (err error) {
    for i := 0; ; i++ {
        err = f()
        if err == nil {
            return
        }

        if i >= (attempts - 1) {
            break
        }

        time.Sleep(sleep)

        log.Println("retrying after error:", err)
    }
    return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
}
like image 84
VonC Avatar answered Oct 10 '22 18:10

VonC