ers

package
v0.10.9 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2024 License: Apache-2.0 Imports: 7 Imported by: 13

Documentation

Overview

Package ers provides some very basic error aggregating and handling tools, as a companion to erc.

The packages are similar, though ers is smaller and has no dependencies outside of a few packages in the standard library, whereas erc is more tightly integrated into fun's ecosystem and programming model.

ers has an API that is equivalent to the standard library errors package, with some additional tools and minor semantic differences.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Append

func Append(errs []error, es ...error) []error

Append adds one or more errors to the error slice, omitting all nil errors.

func As

func As(err error, target any) bool

As is a wrapper around errors.As to allow ers to be a drop in replacement for errors.

func Cast

func Cast(e any) error

Cast converts an untyped/any object into an error, returning nil if the value is not an error or is an error of a nil type.

func ExtractErrors

func ExtractErrors(in []any) (rest []any, errs []error)

Extract iterates through a list of untyped objects and removes the errors from the list, returning both the errors and the remaining items.

func GetTime

func GetTime(err error) time.Time

GetTime unwraps the error looking for an error type that implements the timestamp interface:

interface{ Time() time.Time }

and, if so returns the output of that method. Otherwise, GetTime returns a zeroed time object. Any Error implementation can implement this interface, though the Timestamp type provides a basic implementation.

func Ignore

func Ignore(_ error)

Ignore discards an error.

func Is

func Is(err error, targets ...error) bool

Is returns true if the error is one of the target errors, (or one of it's constituent (wrapped) errors is a target error. ers.Is uses errors.Is.

func IsError

func IsError(err error) bool

IsError returns true when the error is non-nill. Provides the inverse of Ok().

func IsExpiredContext added in v0.10.5

func IsExpiredContext(err error) bool

IsExpiredContext checks an error to see if it, or any of it's parent contexts signal that a context has expired. This covers both canceled contexts and ones which have exceeded their deadlines.

func IsInvariantViolation

func IsInvariantViolation(r any) bool

IsInvariantViolation returns true if the argument is or resolves to ErrInvariantViolation.

func IsTerminating

func IsTerminating(err error) bool

IsTerminating returns true if the error is one of the sentinel errors used by fun (and other packages!) to indicate that processing/iteration has terminated. (e.g. context expiration, or io.EOF.)

func Join

func Join(errs ...error) error

Join takes a slice of errors and converts it into an *erc.Stack typed error. This operation has several advantages relative to using errors.Join(): if you call ers.Join repeatedly on the same error set of errors the resulting error is convertable

func New

func New(str string) error

New constructs an error object that uses the Error as the underlying type.

func NewInvariantViolation added in v0.10.5

func NewInvariantViolation(args ...any) error

NewInvariantViolation creates a new error object, which always includes

func NewWithTime

func NewWithTime(e string) error

NewWithTime creates a new error object with the provided string.

func Ok added in v0.10.9

func Ok(err error) bool

Ok returns true when the error is nil, and false otherwise. It should always be inlined, and mostly exists for clarity at call sites in bool/Ok check relevant contexts.

func ParsePanic

func ParsePanic(r any) error

ParsePanic converts a panic to an error, if it is not, and attaching the ErrRecoveredPanic error to that error. If no panic is detected, ParsePanic returns nil.

func Recover added in v0.10.4

func Recover(ob func(error))

Recovery catches a panic, turns it into an error and passes it to the provided observer function.

func RemoveOk added in v0.10.9

func RemoveOk(errs []error) []error

RemoveOk removes all nil errors from a slice of errors, returning the consolidated slice.

func Strings added in v0.10.4

func Strings(errs []error) []string

Strings renders (using the Error() method) a slice of errors into a slice of their string values.

func Unwind

func Unwind(in error) []error

Unwind, is a special case of the fun.Unwind operation, that assembles the full "unwrapped" list of all component errors. Supports error implementations where the Unwrap() method returns either error or []error.

If an error type implements interface{ Unwind() []error }, this takes precedence over Unwrap when unwinding errors, to better support the Stack type and others where the original error is nested within the unwrapped error objects.

func Unwrap

func Unwrap(err error) error

Unwrap is a wrapper around errors.Unwrap to allow ers to be a drop in replacement for errors.

func When added in v0.10.4

func When(cond bool, val any) error

When constructs an ers.Error-typed error value IF the conditional is true, and returns nil otherwise.

func Whenf added in v0.10.4

func Whenf(cond bool, tmpl string, args ...any) error

Whenf constructs an error (using fmt.Errorf) IF the conditional is true, and returns nil otherwise.

func WithRecoverCall added in v0.10.8

func WithRecoverCall(fn func()) (err error)

WithRecoverCall runs a function without arguments that does not produce an error and, if the function panics, converts it into an error.

func WithRecoverDo added in v0.10.8

func WithRecoverDo[T any](fn func() T) (out T, err error)

WithRecoverDo runs a function with a panic handler that converts the panic to an error.

func WithRecoverOk added in v0.10.9

func WithRecoverOk[T any](fn func() (T, error)) (out T, ok bool)

WithRecoverOk runs a function and returns true if there are no errors and no panics the bool output value is true, otherwise it is false.

func WithTime

func WithTime(err error) error

WithTime wraps an error with a timestamp implementation. The output of time.Now will be captured when WithTime returns, and can be accessed via the GetTime method or using the '%+v' formatting argument.

The Timestamp errors, correctly supports errors.Is and errors.As, passing through to the wrapped error.

func Wrap

func Wrap(err error, annotation ...any) error

Wrap produces a wrapped error if the err is non-nil, wrapping the error with the provided annotation. When the error is nil, Wrap returns nil.

This, roughly mirrors the usage "github/pkg/errors.Wrap" but taking advantage of newer standard library error wrapping.

func WrapRecoverCall added in v0.10.8

func WrapRecoverCall(fn func()) func() error

WrapRecoverCall wraps a function without arguments that does not produce an error with one that does produce an error. When called, the new function will never panic but returns an error if the input function panics.

func WrapRecoverDo added in v0.10.8

func WrapRecoverDo[T any](fn func() T) func() (T, error)

WrapRecoverDo wraps a function that returns a single value, with one that returns that argument and an error if the underlying function panics.

func WrapRecoverOk added in v0.10.9

func WrapRecoverOk[T any](fn func() (T, error)) func() (T, bool)

WrapRecoverOk takes a function that returns an error and a value, and returns a wrapped function that also catches any panics in the input function, and returns the value and a boolean that is true if the input function does not return an error or panic.

func Wrapf

func Wrapf(err error, tmpl string, args ...any) error

Wrapf produces a wrapped error, if the error is non-nil, with a formated wrap annotation. When the error is nil, Wrapf does not build an error and returns nil.

This, roughly mirrors the usage "github/pkg/errors.Wrapf" but taking advantage of newer standard library error wrapping.

Types

type Error

type Error string

Error is a type alias for building/declaring sentinel errors as constants.

In addition to nil error interface values, the Empty string is, considered equal to nil errors for the purposes of Is(). errors.As correctly handles unwrapping and casting Error-typed error objects.

const ErrCurrentOpAbort Error = Error("abort current operation")

ErrCurrentOpAbort is used to signal that a retry function or other looping operation that the loop should exit. ErrCurrentOpAbort should be handled like "break", and should not be returned to callers or aggregated with other errors.

const ErrCurrentOpSkip Error = Error("skip current operation")

ErrCurrentOpSkip is used to signal that a retry function or other looping loop should continue. In most cases, this error should not be returned to callers or aggregated with other errors.

const ErrImmutabilityViolation Error = Error("immutability violation")

ErrImmutabilityViolation is an returned by some operations or invariant violations when an operation attempts to modify logically immutable value.

const ErrInvalidInput Error = Error("invalid input")

ErrInvalidInput indicates malformed input. These errors are not generally retriable.

const ErrInvalidRuntimeType Error = Error("invalid type at runtime")

ErrInvalidRuntimeType signals a type error encountered at runtime. Typically included as a component in an aggregate invariant violation error.

const ErrInvariantViolation Error = Error("invariant violation")

ErrInvariantViolation is the root error of the error object that is the content of all panics produced by the Invariant helper.

const ErrLimitExceeded Error = Error("limit exceeded")

ErrLimitExceeded is a constant sentinel error that indicates that a limit has been exceeded. These are generally retriable.

const ErrMalformedConfiguration Error = Error("malformed configuration")

ErrMalformedConfiguration indicates a configuration object that has failed validation.

const ErrRecoveredPanic Error = Error("recovered panic")

ErrRecoveredPanic is at the root of any error returned by a function in the fun package that recovers from a panic.

func (Error) Err added in v0.10.4

func (e Error) Err() error

Err returns the Error object as an error object (e.g. that implements the error interface.) Provided for more ergonomic conversions.

func (Error) Error

func (e Error) Error() string

Error implements the error interface for ConstError.

func (Error) Is

func (e Error) Is(err error) bool

Satisfies the Is() interface without using reflection.

type Filter

type Filter func(error) error

Filter provides a way to process error messages, either to remove errors, reformulate, or annotate errors.

func FilterCheck

func FilterCheck(ep func(error) bool) Filter

FilterCheck is an error filter that returns nil when the check is true, and false otherwise.

func FilterConvert

func FilterConvert(output error) Filter

FilterConvert returns the provided "output" error for all non-nil errors, and returns nil otherwise.

func FilterExclude

func FilterExclude(exclusions ...error) Filter

FilterExclude takes an error and returns nil if the error is nil, or if the error (or one of its wrapped errors,) is in the exclusion list.

func FilterNoop

func FilterNoop() Filter

FilterNoop produces a filter that always returns the original error.

func FilterToRoot

func FilterToRoot() Filter

FilterToRoot produces a filter which always returns only the root/MOST wrapped error present in an error object.

func (Filter) Run added in v0.10.4

func (f Filter) Run(err error) error

Run runs the filter on the provided error to provide the option of improving readability at callsites

type Stack added in v0.10.4

type Stack struct {
	// contains filtered or unexported fields
}

Stack represents the error type returned by an ErrorCollector when it has more than one error. The implementation provides support for errors.Unwrap and errors.Is, and provides an Errors() method which returns a slice of the constituent errors for additional use.

func AsStack added in v0.10.5

func AsStack(err error) *Stack

AsStack takes an error and converts it to a stack if possible, if the error is an ers.Stack then this is a passthrough, and errors that implement {Unwind() []error} or {Unwrap() []error}, though preferring Unwind, are added individually to the stack.

For errors that provide the Unwind/Unwrap method, if these methods return empty slices of errors, then AsStack will return nil.

func (*Stack) Add added in v0.10.5

func (e *Stack) Add(errs ...error)

Add is a thin wrapper around Push, that adds each error supplied as an argument individually to the stack.

This leads to a curios, semantic: using the Unwrap() method (and casting; but not the unwind method!), the values returned for each layer are also *ers.Stack values: if you were to call Add any of these objects, you would end up with sort of tree-like assortment of objects which may yield surprising result. At the same time, if you have a reference to one of these stack objects, future calls to Add() on the "outer" stack will have no bearing on "inner" Stack objects.

func (*Stack) As added in v0.10.4

func (e *Stack) As(target any) bool

As calls errors.As on the underlying error to provied compatibility with errors.As, which takes advantage of this interface.

func (*Stack) CheckProducer added in v0.10.4

func (e *Stack) CheckProducer() func() (error, bool)

CheckProducer provides a pull-based iterator function for iterating through the errors (without Stack object wrappers.) The output function yields errors: the boolean return

func (*Stack) Error added in v0.10.4

func (e *Stack) Error() string

Error produces the aggregated error strings from this method. If the error at the current layer is nil.

func (*Stack) Future added in v0.10.5

func (e *Stack) Future() func() error

Future provides a fun.Future[error] typed function (though because ers is upstream of the root-fun package, it is not explicitly typed as such.) which will resolve the stack.

func (*Stack) Handler added in v0.10.5

func (e *Stack) Handler() func(err error)

Handler provides a fun.Handler[error] typed function (though because ers is upstream of the root-fun package, it is not explicitly typed as such.) which will Add errors to the stack.

func (*Stack) Is added in v0.10.4

func (e *Stack) Is(err error) bool

Is calls errors.Is on the underlying error to provied compatibility with errors.Is, which takes advantage of this interface.

func (*Stack) Len added in v0.10.4

func (e *Stack) Len() int

Len returns the depth of the stack beneath the current level. This value isn't updated as additional errors are pushed onto the stack.

func (*Stack) Ok added in v0.10.9

func (e *Stack) Ok() bool

Ok returns true if the Stack object contains no errors and false otherwise.

func (*Stack) Push added in v0.10.4

func (e *Stack) Push(err error)

Push adds an error to the current stack. If one stack is pushed onto another, the first stack's errors are unwound and pushed individually to the stack. If the error object implements the {Unwind() []error}, or {Unwrap() []error} interfaces, then these are also pushed individually to the stack, all other errors are added individually to the stack. The Stack.Is() and Stack.As implementations support identfying all errors included in the stack even if one of the individual errors is itself wrapped (e.g. one wrapped using fmt.Errorf and %w.)

The stack object is not safe for concurrent access (use the error collector in the `erc` package for a higher level interface to the Stack object that includes a mutex,) but, Stack objects are implemented as a linked list and not modified after use, which may make them easier to reason about.

func (*Stack) Resolve added in v0.10.6

func (e *Stack) Resolve() error

Resolve, mirroring the interface of erc.Collector, returns the error (always a Stack object containing the aggregate errors,) in the case that stack object contains errors, and nil otherwise.

func (*Stack) Unwind added in v0.10.4

func (e *Stack) Unwind() []error

Unwind returns a slice of the errors included in the Stack directly without wrapping them as Stacks. The ers.Unwind function *does* take advantage of this interface, although, in practice special cases the Stack type.

func (*Stack) Unwrap added in v0.10.4

func (e *Stack) Unwrap() error

Unwrap returns the next iterator in the stack, and is compatible with errors.Unwrap. The error objects returned by unwrap are all Stack objects. When the

Jump to

Keyboard shortcuts

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