errorutil

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: May 11, 2021 License: MIT Imports: 5 Imported by: 0

README

errorutil Travis-CI GoDoc

go get github.com/objenious/errorutil

Delayed errors

func foo() error {
	err := bar()
	timer := time.Hour
	if err != nil {
		// it should be delayed 1h later
		return errorutil.WithDelay(err, timer) 
	}
	return bar() // will not be delayed
}

func main() {
	err := foo()
	time.AfterFunc(errorutil.Delay(err), func() {
		...
	})
}

Retryable errors

func foo() error {
  err := bar()
  if err != nil {
    // it should be retried
    return errorutil.RetryableError(err)
  }
  return baz() // will not be retried
}

func main() {
  err := foo()
  if errorutil.IsRetryable(err) {
    // retry !
  }
}

HTTP Aware errors

Build an error based on a http.Response. Status code above 299, except 304, will be considered an error.

It will be retryable if status code is http.StatusBadGateway, http.StatusGatewayTimeout, http.StatusServiceUnavailable, http.StatusInternalServerError or 429 (Too many requests).

resp, err := http.Get("http://www.example.com")
if err != nil {
  // return error
}
defer resp.Body.Close()
if err := errorutil.HTTPError(resp); err != nil {
  // return error
}
// handle response

Find the most appropriate status code for an error :

w.WriteHeader(errorutil.HTTPStatusCode(err))

Generate specific error types :

err := errors.New("some error")
err = errorutil.NotFoundError(err)
w.WriteHeader(errorutil.HTTPStatusCode(err)) // returns http.StatusNotFound

Exponential backoff

backoffutil.Retry(func() error {
  resp, err := http.Get("http://www.example.com")
  if err != nil {
    return err
  }
  defer resp.Body.Close()
  if err := errorutil.HTTPError(resp); err != nil {
    return err
  }
  // Do something
  return nil
})

Notes

errorutil is compatible with https://github.com/objenious/errors :

err = errors.Wrap(errorutil.RetryableError(err), "some message")
errorutil.IsRetryable(err) // returns true

Documentation

Overview

Package errorutil allows errors to be tagged, allowing calling code to make decisions, such as "is the error retryable ?" or "what kind of HTTP status code should I return ?".

Retryable errors

Mark errors as retryable :

func foo() error {
  err := bar()
  if err != nil {
    // should be retried
    return errorutil.RetryableError(err)
  }
  return baz() // should not be retried
}

func main() {
  err := foo()
  if errorutil.IsRetryable(err) {
    // retry !
  }
}

HTTP Aware errors

Build an error based on a http.Response. It will be retryable of status code is http.StatusBadGateway, http.StatusGatewayTimeout, http.StatusServiceUnavailable, http.StatusInternalServerError or 429 (Too many requests).

resp, err := http.Get("http://www.example.com")
if err != nil {
  // return error
}
defer resp.Body.Close()
if err := errorutil.HTTPError(resp); err != nil {
  // return error
}
// handle response

Find the most appropriate status code for an error :

w.WriteHeader(errorutil.HTTPStatusCode(err))

Generate specific error types :

err := errors.New("some error")
err = errorutil.NotFoundError(err)
w.WriteHeader(errorutil.HTTPStatusCode(err)) // returns http.StatusNotFound

Exponential backoff

see backoffutil sub package

Notes

errorutil is compatible with https://github.com/objenious/errors :

err = errors.Wrap(errorutil.RetryableError(err), "some message")
errorutil.IsRetryable(err) // returns true

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConflictError

func ConflictError(err error) error

ConflictError marks an error as "conflict". The calling http handler should return a Conflict status code. It returns nil if the error is nil.

Example
var w http.ResponseWriter
err := errors.New("some error")
err = ConflictError(err)
w.WriteHeader(HTTPStatusCode(err)) // returns http.StatusConflict

func Delay added in v0.0.2

func Delay(err error) time.Duration

Delay return the delay duration of a DelayedError (i.e. implements Delayer). If the error is nil or does not implement Delayer or the delay is not a positive value, 0 is returned.

func ForbiddenError

func ForbiddenError(err error) error

ForbiddenError marks an error as "access forbidden". The calling http handler should return a StatusForbidden status code. It returns nil if the error is nil.

Example
var w http.ResponseWriter
err := errors.New("some error")
err = ForbiddenError(err)
w.WriteHeader(HTTPStatusCode(err)) // returns http.StatusForbidden

func HTTPError

func HTTPError(resp *http.Response) error

HTTPError builds an error based on a http.Response. If status code is < 300 or 304, nil is returned. Otherwise, errors implementing the various interfaces (Retryabler, HTTPStatusCodeEr) are returned

Example
resp, err := http.Get("http://www.example.com")
if err != nil {
	// return error
}
defer resp.Body.Close()
if err := HTTPError(resp); err != nil {
	// return error
}
// handle response

func HTTPStatusCode

func HTTPStatusCode(err error) int

HTTPStatusCode returns the status code that a HTTP handler should return.

If the error is nil, StatusOK is returned.

If the error implements HTTPStatusCodeEr or StatusCodeEr, it returns the corresponding status code.

It tries to check some stdlib errors (testing the error string, to avoid importing unwanted packages), and returns appropriate status codes.

Otherwise, StatusInternalServerError is returned.

func InvalidError

func InvalidError(err error) error

InvalidError marks an error as "invalid". The calling http handler should return a StatusBadRequest status code. It returns nil if the error is nil.

Example
var w http.ResponseWriter
err := errors.New("some error")
err = InvalidError(err)
w.WriteHeader(HTTPStatusCode(err)) // returns http.StatusBadRequest

func IsNotRetryable

func IsNotRetryable(err error) bool

IsNotRetryable checks if an error is explicitly marked as not retryable (i.e. implements Retryabler and Retryable returns false).

If the error is nil or does not implement Retryabler, false is returned.

Example
err := errors.New("some error")
IsNotRetryable(err) // will return false
err = RetryableError(err)
IsNotRetryable(err) // will return false

func IsRetryable

func IsRetryable(err error) bool

IsRetryable checks if an error is retryable (i.e. implements Retryabler and Retryable returns true).

If the error is nil or does not implement Retryabler, false is returned.

Example
err := errors.New("some error")
IsRetryable(err) // will return false
err = RetryableError(err)
IsRetryable(err) // will return true
//err = NotRetryableError(err)
IsRetryable(err) // will return false

func NewDelayedError added in v0.0.2

func NewDelayedError(text string, duration time.Duration) error

NewDelayedError returns a delayed error that formats as the given text and duration.

func NewRetryableError

func NewRetryableError(text string) error

NewRetryableError returns a retryable error that formats as the given text.

Example
err := NewRetryableError("test")
IsRetryable(err) // will return true

func NewRetryableErrorf

func NewRetryableErrorf(format string, args ...interface{}) error

NewRetryableErrorf formats according to a format specifier and returns the string as a value that satisfies a retryable error.

Example
err := NewRetryableErrorf("Unable to read data for device %d", 70)
IsRetryable(err) // will return true

func NotFoundError

func NotFoundError(err error) error

NotFoundError marks an error as "not found". The calling http handler should return a StatusNotFound status code. It returns nil if the error is nil.

Example
var w http.ResponseWriter
err := errors.New("some error")
err = NotFoundError(err)
w.WriteHeader(HTTPStatusCode(err)) // returns http.StatusNotFound

func NotRetryableError

func NotRetryableError(err error) error

NotRetryableError marks an error as NOT retryable. It returns nil if the error is nil.

func RetryableError

func RetryableError(err error) error

RetryableError marks an error as retryable. It returns nil if the error is nil.

func WithDelay added in v0.0.2

func WithDelay(err error, duration time.Duration) error

DelayedError set error delay duration. returns nil if the error is nil.

Types

type Delayer added in v0.0.2

type Delayer interface {
	Delay() time.Duration
}

Delayer defines an error that

type HTTPStatusCodeEr

type HTTPStatusCodeEr interface {
	HTTPStatusCode() int
}

HTTPStatusCodeEr defines errors that should return a specific HTTP status code

type Retryabler

type Retryabler interface {
	Retryable() bool
}

Retryabler defines an error that may be temporary. A function returning a retryable error should be executed again.

type StatusCodeEr

type StatusCodeEr interface {
	StatusCode() int
}

StatusCodeEr defines errors that should return a specific HTTP status code

Directories

Path Synopsis
Package backoffutil provides a wrapper above github.com/cenk/backoff.Retry that checks the error returned and only retries retryable errors.
Package backoffutil provides a wrapper above github.com/cenk/backoff.Retry that checks the error returned and only retries retryable errors.

Jump to

Keyboard shortcuts

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