errors

package
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2022 License: MIT Imports: 12 Imported by: 2

Documentation

Overview

Package errors is a drop-in replacement for the errors package in the standard library, with extensions useful for developing web applications.

Index

Constants

View Source
const (
	StatusBadRequest                   = Standard(http.StatusBadRequest)
	StatusUnauthorized                 = Standard(http.StatusUnauthorized)
	StatusPaymentRequired              = Standard(http.StatusPaymentRequired)
	StatusForbidden                    = Standard(http.StatusForbidden)
	StatusNotFound                     = Standard(http.StatusNotFound)
	StatusMethodNotAllowed             = Standard(http.StatusMethodNotAllowed)
	StatusNotAcceptable                = Standard(http.StatusNotAcceptable)
	StatusProxyAuthRequired            = Standard(http.StatusProxyAuthRequired)
	StatusRequestTimeout               = Standard(http.StatusRequestTimeout)
	StatusConflict                     = Standard(http.StatusConflict)
	StatusGone                         = Standard(http.StatusGone)
	StatusLengthRequired               = Standard(http.StatusLengthRequired)
	StatusPreconditionFailed           = Standard(http.StatusPreconditionFailed)
	StatusRequestEntityTooLarge        = Standard(http.StatusRequestEntityTooLarge)
	StatusRequestURITooLong            = Standard(http.StatusRequestURITooLong)
	StatusUnsupportedMediaType         = Standard(http.StatusUnsupportedMediaType)
	StatusRequestedRangeNotSatisfiable = Standard(http.StatusRequestedRangeNotSatisfiable)
	StatusExpectationFailed            = Standard(http.StatusExpectationFailed)
	StatusTeapot                       = Standard(http.StatusTeapot)
	StatusMisdirectedRequest           = Standard(http.StatusMisdirectedRequest)
	StatusUnprocessableEntity          = Standard(http.StatusUnprocessableEntity)
	StatusLocked                       = Standard(http.StatusLocked)
	StatusFailedDependency             = Standard(http.StatusFailedDependency)
	StatusTooEarly                     = Standard(http.StatusTooEarly)
	StatusUpgradeRequired              = Standard(http.StatusUpgradeRequired)
	StatusPreconditionRequired         = Standard(http.StatusPreconditionRequired)
	StatusTooManyRequests              = Standard(http.StatusTooManyRequests)
	StatusRequestHeaderFieldsTooLarge  = Standard(http.StatusRequestHeaderFieldsTooLarge)
	StatusUnavailableForLegalReasons   = Standard(http.StatusUnavailableForLegalReasons)

	StatusInternalServerError           = Standard(http.StatusInternalServerError)
	StatusNotImplemented                = Standard(http.StatusNotImplemented)
	StatusBadGateway                    = Standard(http.StatusBadGateway)
	StatusServiceUnavailable            = Standard(http.StatusServiceUnavailable)
	StatusGatewayTimeout                = Standard(http.StatusGatewayTimeout)
	StatusHTTPVersionNotSupported       = Standard(http.StatusHTTPVersionNotSupported)
	StatusVariantAlsoNegotiates         = Standard(http.StatusVariantAlsoNegotiates)
	StatusInsufficientStorage           = Standard(http.StatusInsufficientStorage)
	StatusLoopDetected                  = Standard(http.StatusLoopDetected)
	StatusNotExtended                   = Standard(http.StatusNotExtended)
	StatusNetworkAuthenticationRequired = Standard(http.StatusNetworkAuthenticationRequired)
)

Standard HTTP status codes as errors.

Variables

This section is empty.

Functions

func Append added in v0.2.0

func Append(err error, errs ...error) error

Append joins zero or more errors into a single error. Any nil values are excluded, returning nil if all inputs are nil. Any multi-errors in the input are treated as multiple errors. If the final result is a single error, it is returned unaltered, otherwise a multi-error value is returned, which can in turn be exploded by calling the Errors() method.

func As

func As(err error, target interface{}) bool

As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true. Otherwise, it returns false.

The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.

An error matches target if the error's concrete value is assignable to the value pointed to by target, or if the error has a method As(interface{}) bool such that As(target) returns true. In the latter case, the As method is responsible for setting target.

An error type might provide an As method so it can be treated as if it were a different error type.

As panics if target is not a non-nil pointer to either a type that implements error, or to any interface type.

func AttachStack added in v0.4.0

func AttachStack(err error, st StackTrace) error

AttachStack annotates err with the provided stack trace.

func Errorf

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

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

If the format specifier includes a %w verb with an error operand, the returned error will implement an Unwrap method returning the operand. It is invalid to include more than one %w verb or to supply it with an operand that does not implement the error interface. The %w verb is otherwise a synonym for %v.

Errorf also records the stack trace at the point it was called.

func ExtractGRPCCode added in v0.27.0

func ExtractGRPCCode(err error) (codes.Code, bool)

ExtractGRPCCode works just like ExtractGRPCCode, but returns only the status code.

func ExtractGRPCStatus added in v0.27.0

func ExtractGRPCStatus(err error) (*status.Status, bool)

ExtractGRPCStatus works just like the standard status.FromError(), except that it works on wrapped errors as well. The bool value will be true if err wraps a GRPCStatus error. If err is not a GRPCStatus error, a Status with code.Unknown is returned. If err is nil, a status with code OK and message OK is returned.

func ExtractHTTPStatus added in v0.27.0

func ExtractHTTPStatus(err error) (int, bool)

ExtractHTTPStatus returns the outter-most HTTP status in the error stack. The bool value will be true if err includes an explicit HTTP status code.

If err is nil, 0 is returned.

If no HTTP status is found, http.StatusInternalServerError is returned.

This function understand HTTPStatusErrors (i.e. interface { HTTPStatus() int }), as well as echo3 and echo4 HTTPError type.

func HTTPStatusf

func HTTPStatusf(status int, format string, args ...interface{}) error

HTTPStatusf works like calling WithHTTPStatus(status, Errorf(format, args ...)).

func InspectErrors added in v0.2.1

func InspectErrors(err error) []error

InspectErrors explodes a multi-error, such as that returned by Append, and returns a slice of the underlying errors. If err is not a multi-error, it will be the only element in the returned slice.

Any error which satisfies the following method is considered a multi-error:

type multiError interface {
	Errors() error
}

func InspectFields

func InspectFields(err error) map[string]interface{}

InspectFields traverses the entire error chain, looking for embedded fields. In case of duplicate keys, the outter-most value takes precident. If no field annotations are found, nil is returned.

func InspectGRPCCode added in v0.25.0

func InspectGRPCCode(err error) codes.Code

InspectGRPCCode works just like InspectGRPCStatus, but returns only the status code.

func InspectGRPCStatus added in v0.25.0

func InspectGRPCStatus(err error) *status.Status

InspectGRPCStatus is like ExtractGRPCStatus, but disregards the bool value.

func InspectHTTPStatus

func InspectHTTPStatus(err error) int

InspectHTTPStatus returns the outter-most HTTP status in the error stack.

If err is nil, 0 is returned.

If no HTTP status is found, http.StatusInternalServerError is returned.

This function understand HTTPStatusErrors (i.e. interface { HTTPStatus() int }), as well as echo3 and echo4 HTTPError type.

TODO: Support gRPC and Twirp errors.

func InspectRetryAfter added in v0.8.0

func InspectRetryAfter(err error) string

InspectRetryAfter returns the outter-most RetryAfter value in the error stack.

If err is nil, there is no RetryAfter value found, or the RetryAfter value is blank (as when set by WithoutRetryAfter), the empty string is returned.

func Internal added in v0.3.0

func Internal(err error) error

Internal promotes err to an Internal Server Error. Shorter equivalent of WithHTTPStatus(err, http.StatusInternalServerError)

func Is

func Is(err, target error) bool

Is reports whether any error in err's chain matches target.

The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.

An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.

An error type might provide an Is method so it can be treated as equivalent to an existing error. For example, if MyError defines

func (m MyError) Is(target error) bool { return target == fs.ErrExist }

then Is(MyError{}, fs.ErrExist) returns true. See syscall.Errno.Is for an example in the standard library.

func MustLog added in v0.9.0

func MustLog(err error) error

MustLog flags that an error should be logged, regardless of its HTTP status.

func New

func New(message string) error

New returns an error with the supplied message. New also records the stack trace at the point it was called.

func ReadChan added in v0.2.1

func ReadChan(errCh <-chan error) error

ReadChan reads errors from an error channel, until the channel is closed, returning a multi-error. To inspect the individual errors, use the Errors() method, or use the InspectErrors function.

func ReadChanN added in v0.2.1

func ReadChanN(errCh <-chan error, n int) error

ReadChanN reads up to n errors from an error channel, returning a multi-error. To inspect the individual errors, use the Errors() method, or use the InspectErrors function.

When n values (including nils) are read, or errCh is closed, the function returns. If n=0, there is no limit.

func Unwrap

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.

func WithField

func WithField(err error, key string, value interface{}) error

WithField annotates err with the provided key/value pair, which can be inspected with the InspectFields() function. It also adds the stacktrace where WithField is called. If err is nil, nil is returned.

func WithFields

func WithFields(err error, fields Fields) error

WithFields annotates err with the provided fields, which can be inspected with the InspectFields() function. It also adds the stacktrace where WithFields is called.

func WithHTTPStatus

func WithHTTPStatus(err error, status int) error

WithHTTPStatus annotates err with the provided HTTP status. If err is nil, WithHTTPStatus returns nil.

func WithRetryAfter added in v0.8.0

func WithRetryAfter(err error, t time.Time) error

WithRetryAfter wraps err such that when queried with InspectRetryAfter, it will return a RetryAfter value based on t.

func WithRetryAfterDur added in v0.8.0

func WithRetryAfterDur(err error, dur time.Duration) error

WithRetryAfterDur wraps err such that when queried with InspectRetryAfter, it will return a RetryAfter header based on dur.

func WithStack

func WithStack(err error) error

WithStack annotates err with a stack trace at the point WithStack was called. If err is nil, WithStack returns nil.

func WithStackN added in v0.6.0

func WithStackN(err error, skip int) error

WithStackN annotates err with a stack trace at the point WithStackN was called, minus skip frames. If err is nil, WithStack returns nil.

func WithoutRetryAfter added in v0.8.0

func WithoutRetryAfter(err error) error

WithoutRetryAfter will wrap err with an error that returns an empty string for a RetryAfter query.

Types

type Fields

type Fields map[string]interface{}

Fields represents arbitrary key/value fields with which errors may be annotated. This is intended for use with structured logging systems such as logrus.

type Frame

type Frame = pkgerrors.Frame

Frame represents a program counter inside a stack frame. For historical reasons if Frame is interpreted as a uintptr its value represents the program counter + 1.

type Notes

type Notes interface {
	// HTTPStatus returns a new Notes instance which wraps the original and
	// adds the provided HTTP status.
	HTTPStatus(int) Notes
	// Field returns a new Notes instance which wraps the original and adds the
	// provided key/value field pair.
	Field(string, interface{}) Notes
	// Fields returns a new Notes instance which wraps the original and adds
	// the provided fields.
	Fields(Fields) Notes
	// Wrap annotates the provided error with the annotations. If error is nil
	// nil is returned. A stacktrace is also added where Wrap is called (unless
	// NoStack() has been called).
	Wrap(error) error
	// Errorf returns a new error annotated with the annotations. Equivalent to
	// Wrap(fmt.Errorf(format, args...)).
	Errorf(format string, args ...interface{}) error
	// NoStack returns a new Notes instance which will not include a stack
	// trace when Wrap() is called.
	NoStack() Notes
	// RetryAfter returns a new Notes instance which wraps the original and
	// adds the provided RetryAfter value based on t.
	RetryAfter(time.Time) Notes
	// RetryAfterDur returns a new Notes instance which wraps the original and
	// adds the provided RetryAfter value based on dur.
	RetryAfterDur(time.Duration) Notes
	// NoRetryAfter returns a new Notes instance which wraps the original and
	// adds a blank RetryAfter value.
	NoRetryAfter() Notes
	// StackN instructs the Wrap function to attach a stack trace with s frames
	// skipped.
	StackN(s uint) Notes
}

Notes is a collection of zero or more error annotations, which can be attached to an error.

func NewNotes

func NewNotes() Notes

NewNotes returns an empty Notes collection.

type StackTrace

type StackTrace = pkgerrors.StackTrace

StackTrace is stack of Frames from innermost (newest) to outermost (oldest).

func Callers added in v0.11.0

func Callers(n int) StackTrace

Callers generates a StackTrace. If n > 0, n frames are skipped.

func InspectDeepStackTrace added in v0.4.0

func InspectDeepStackTrace(err error) StackTrace

InspectDeepStackTrace returns the last (inner-most) stacktrace in error, or nil if none is found

func InspectStackTrace added in v0.4.0

func InspectStackTrace(err error) StackTrace

InspectStackTrace returns the first (outter-most) stacktrace in err, or nil if none is found.

type Standard

type Standard int

Standard converts a standard HTTP status code into a useable error

func (Standard) Error

func (e Standard) Error() string

func (Standard) HTTPStatus

func (e Standard) HTTPStatus() int

HTTPStatus returns the HTTP status associated with the error.

Jump to

Keyboard shortcuts

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