1

I've tried to create a function in Go that used to retry any fail query functions (usually because serialization issue).

func retryer(functionA func(interface{}) (interface{}, []error), maxRetry int, waitBetween time.Duration) interface{} { //when no error in functionA, retryer returns whatever functionA returns //when maxRetry is reached, returns nil } 

The functions I want to retry are looked like this

func GetTopStudent(classId string) ([]Student, []error) { //queries top 10 students for class with classId } func GetAverageStudentScores(classId string, from time.Time, until time.Time) ([]Pair, []error) { //queries all average score using aggregate, grouping by studentId //Pair behaves like C++ pair<string,string> } 

But, the results is a compile error

cannot use GetTopStudent (type func(string) ([]Student, []error)) as type func(interface{}) (interface {}, []error) in argument to retryer 

I've tried to modify it a little and I got another compile error

cannot use GetTopStudent (type func(string) ([]Student, []error)) as type func(string) (interface {}, []error) in argument to retryer 

Can anyone help me creating a general function to wrap a function to retry on error?

3
  • 2
    The signatures of the functions passed as a parameter must match the signature of the function type of the parameter exactly. You'll have to rewrite the functions you pass to take interface{}'s, and cast them to the appropriate types inside those functions. Commented Jun 14, 2017 at 4:13
  • That way, for N functions, I need N wrappers. I need the general function wrapper to greatly simplify me code. Commented Jun 14, 2017 at 4:25
  • 1
    Yes. Or redesign. Commented Jun 14, 2017 at 4:26

1 Answer 1

3

A better way to solve your problem would be to use closures.

For example, change the type of retryer:

func retryer(f func() error, maxRetry int, waitBetween time.Duration) error { // retry and wait logic err := f() // error handling, retry, and wait logic return err } 

Now call functions to be retried as:

// ... classId := "some value" // ... var st []Student var errors []error err := retryer(func() error { st, errors = GetTopStudent(classId) // handle errors return nil }, numTries, waitTime) // use st here 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.