Skip to content

Commit

Permalink
helper/resource: RetryError for quitting quickly
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchellh committed Oct 18, 2014
1 parent 10ce2b6 commit b4f8b7f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
21 changes: 18 additions & 3 deletions helper/resource/wait.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,29 @@ func Retry(timeout time.Duration, f RetryFunc) error {
MinTimeout: 500 * time.Millisecond,
Refresh: func() (interface{}, string, error) {
err = f()
if err != nil {
return 42, "error", nil
if err == 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()
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()
}
23 changes: 23 additions & 0 deletions helper/resource/wait_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,26 @@ func TestRetry_timeout(t *testing.T) {
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")
}
}

0 comments on commit b4f8b7f

Please sign in to comment.