helper/resource: RetryError for quitting quickly

This commit is contained in:
Mitchell Hashimoto 2014-10-17 18:28:03 -07:00
parent 10ce2b690c
commit b4f8b7f43b
2 changed files with 41 additions and 3 deletions

View File

@ -18,14 +18,29 @@ func Retry(timeout time.Duration, f RetryFunc) error {
MinTimeout: 500 * time.Millisecond, MinTimeout: 500 * time.Millisecond,
Refresh: func() (interface{}, string, error) { Refresh: func() (interface{}, string, error) {
err = f() err = f()
if err != nil { if err == nil {
return 42, "error", nil return 42, "success", nil
} }
return 42, "success", nil if rerr, ok := err.(RetryError); ok {
err = rerr.Err
return nil, "quit", err
}
return 42, "error", nil
}, },
} }
c.WaitForState() c.WaitForState()
return err return err
} }
// RetryError, if returned, will quit the retry immediately with the
// Err.
type RetryError struct {
Err error
}
func (e RetryError) Error() string {
return e.Err.Error()
}

View File

@ -37,3 +37,26 @@ func TestRetry_timeout(t *testing.T) {
t.Fatal("should error") t.Fatal("should error")
} }
} }
func TestRetry_error(t *testing.T) {
t.Parallel()
expected := fmt.Errorf("nope")
f := func() error {
return RetryError{expected}
}
errCh := make(chan error)
go func() {
errCh <- Retry(1*time.Second, f)
}()
select {
case err := <-errCh:
if err != expected {
t.Fatalf("bad: %#v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("timeout")
}
}