Handle and inspect retry errors
mainWhen a retry operation fails, it returns an Error type, which is a slice of all errors encountered during the attempts. This type implements the Go 1.20 Unwrap() []error interface.
To inspect errors:
- Recommended: Use standard library
errors.Is(err, target)orerrors.As(err, &target)to check all wrapped errors. - Get the last error: If you specifically need the final error that caused the failure, cast the error to
retry.Errorand call.LastError(). - Unrecoverable errors: Wrap an error with
retry.Unrecoverable(err)to stop retries immediately.
// Use errors.Is to check for specific errors
err := retry.New(retry.Attempts(3)).Do(func() error {
return os.ErrNotExist
})
if errors.Is(err, os.ErrNotExist) {
// Handle not exist error
}
// Use errors.As to extract error details
var pathErr *fs.PathError
if errors.As(err, &pathErr) {
fmt.Println("Failed at path:", pathErr.Path)
}
// Get the last error directly (migration path from v4)
if retryErr, ok := err.(retry.Error); ok {
lastErr := retryErr.LastError()
}