package main
import "fmt"
func test(i int){
defer func(){
if r := recover(); r != nil {
fmt.Println("Inside Recover: ", r)
}
}()
for try := 1 ; try <= i ; try++{
if (i == 3){
panic("Panic")
}
fmt.Printf("i: %d try: %d
", i , try)
}
}
func main(){
for i := 1 ; i < 5 ; i++{
test(i)
}
}
The method panics and skips to next i
value without trying i
times. Is there a way in which we can recover from the panic and retry for the same value of i
that caused panic ?
I am assuming you wanted to test any function that could fail with this construct, best without having to change that function. Here my solution. Hope this is what you were looking for.
package main
import (
"errors"
"fmt"
)
func test(i int) error {
if i == 3 {
return errors.New("Panic")
}
return nil
}
func retryWrapper(i, try int) {
err := test(i)
fmt.Printf("i: %d try: %d
", i, try)
if err != nil && try < 5 {
retryWrapper(i, try+1)
}
}
func main() {
for i := 1; i < 5; i++ {
retryWrapper(i, 1)
}
}
This works with functions that return an error. If your function panics, you will need to change the test function with a defer/recover like this:
func test(i int) (err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New(r.(string))
}
}()
if i == 3 {
panic("Panic")
}
return
}
Note: retry is limited to 5 trys to prevent an infinite loop.