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 ?
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!
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.
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With