retry

package
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 30, 2022 License: Apache-2.0 Imports: 1 Imported by: 1

Documentation

Overview

Example

Shows how to wrap a sample function into an invocation for use with the Retry function.

package main

import (
	"errors"
	"fmt"

	"github.com/trustbloc/edge-core/pkg/utils/retry"
)

// Shows how to wrap a sample function into an invocation for use with the Retry function.
func main() {
	var marsWeather string

	fetcher := weatherFetcher{}

	// InitialBackoff and BackoffFactor are set to zero here in order to ensure this example runs quickly,
	// but normally you would want to pick reasonable values.
	retryParams := retry.Params{
		MaxRetries:     5,
		InitialBackoff: 0,
		BackoffFactor:  0,
	}

	err := retry.Retry(func() error {
		var weatherCallErr error
		marsWeather, weatherCallErr = fetcher.getWeatherOnMars()

		return weatherCallErr
	}, &retryParams)
	if err != nil {
		fmt.Println("exhausted all retries. Last error was: " + err.Error())
	}

	fmt.Println(marsWeather)

}

type weatherFetcher struct {
	timesRun int
}

// A simulated REST API call that you may expect to fail sometimes.
func (w *weatherFetcher) getWeatherOnMars() (string, error) {
	if w.timesRun == 4 {
		return "-80 degrees and sunny", nil
	}

	w.timesRun++

	return "", errors.New("interference from space debris")
}
Output:

-80 degrees and sunny

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Retry

func Retry(invocation Invocation, params *Params) error

Retry retries the given Invocation based on the given Params until it returns no error, at which point this function returns no error as well. If the retry attempts are exhausted, this function returns the most recent error returned from the given Invocation.

Types

type Invocation

type Invocation func() error

Invocation represents a function that is desired to be retried until it succeeds (i.e. it returns nil).

type Params

type Params struct {
	MaxRetries     uint
	InitialBackoff time.Duration
	BackoffFactor  float64
}

Params are used to define how retry attempts are handled.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL