Skip to content

Commit

Permalink
refactor error format
Browse files Browse the repository at this point in the history
  • Loading branch information
window9u committed Dec 30, 2024
1 parent 34fa918 commit b7add32
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions pkg/webhook/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ var (
// ErrUnexpectedStatusCode is returned when the webhook returns an unexpected status code.
ErrUnexpectedStatusCode = errors.New("unexpected status code from webhook")

// ErrWebhookTimeout is returned when the webhook times out.
ErrWebhookTimeout = errors.New("webhook timeout")
// ErrMaxRetriesExceeded indicates we have retried up to the specified max retries
// without a successful outcome.
ErrMaxRetriesExceeded = errors.New("exponential backoff: maximum retries exceeded")
)

// WithExponentialBackoff retries the given webhookFn with exponential backoff.
Expand All @@ -42,8 +43,13 @@ func WithExponentialBackoff(
maxInterval gotime.Duration,
webhookFn func() (int, error),
) error {
var retries uint64
var statusCode int
start := gotime.Now()

var (
retries uint64
statusCode int
)

for retries <= maxRetries {
statusCode, err := webhookFn()
if !shouldRetry(statusCode, err) {
Expand All @@ -65,7 +71,13 @@ func WithExponentialBackoff(
retries++
}

return fmt.Errorf("unexpected status code from webhook %d: %w", statusCode, ErrWebhookTimeout)
return fmt.Errorf(
"maximum retries (%d) exceeded after %s; last status code = %d: %w",
maxRetries,
gotime.Since(start),
statusCode,
ErrMaxRetriesExceeded,
)
}

// waitInterval returns the interval of given retries. it returns maxWaitInterval
Expand Down

0 comments on commit b7add32

Please sign in to comment.