stdlib

package
v1.39.0 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2024 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrTypeAssertionFailed = Error{
	Code:      "type_assertion_failed",
	Message:   "type assertion failed",
	Namespace: ErrorNamespaceDefault,
}

ErrTypeAssertionFailed is returned when attempting to type assert a value that cannot be converted.

View Source
var ErrTypeConversionFailed = Error{
	Code:      "type_conversion_failed",
	Message:   "type conversion failed",
	Namespace: ErrorNamespaceDefault,
}

ErrTypeConversionFailed is returned when attempting a type conversion that cannot be performed.

View Source
var ErrUndefined = Error{
	Code:      "undefined",
	Flags:     ErrorFlagUnknown,
	Message:   "error is not defined",
	Namespace: ErrorNamespaceDefault,
}

ErrUndefined indicates the wrapped error is not well-known or previously defined. This likely means it's coming from an external system/library and not a domain error.

Functions

func AnyTo added in v1.32.0

func AnyTo[T any](v any) any

AnyTo converts an any interface value to a value that can be type asserted to type T.

func As added in v1.33.0

func As[T any](v any) (T, error)

As performs a type assertion of 'any' value to type T. If it fails an error is returned.

func Build added in v1.17.0

func Build[T any](t T, builders ...Builder[T]) (T, error)

Build applies all functional builders to type t and returns the type built.

func Defer added in v1.6.0

func Defer(err *error, errs ...error)

Defer is a helper for capturing errors from calls inside a 'defer'.

func DeferCall added in v1.29.0

func DeferCall(err *error, fn func() error)

DeferCall is a helper for deferring a function call (closer) that can return an error when in a function context that can return multiple errors.

func DeferCloser added in v1.28.0

func DeferCloser(err *error, closer io.Closer)

DeferCloser is a helper for deferring a io.Closer that can return an error when in a function context that can return multiple errors.

func ErrorGroupFormatterDefault

func ErrorGroupFormatterDefault(errors []Error) string

ErrorGroupFormatterDefault is a basic Formatter that outputs the number of errors that occurred along with a bullet point list of the errors.

func ErrorKey added in v1.27.0

func ErrorKey(namespace, code string) string

ErrorKey returns a slug that should be unique for each error (namespace + code).

func IsZero

func IsZero[T any](t T) bool

IsZero returns true if the given value is equal to the zero value of the type.

func IsZeroAny added in v1.19.0

func IsZeroAny(t any) bool

IsZeroAny returns true if the given value is equal to the zero value of the type.

func MapFilter

func MapFilter[K comparable, V any](input map[K]V, predicate KeyedPredicate[K, V]) map[K]V

MapFilter will return a new map containing only items from the input map that match the predicate function.

func MapFilterRange

func MapFilterRange[K comparable, V any](input KeyedRanger[K, V], predicate KeyedPredicate[K, V]) map[K]V

MapFilterRange will return a new map containing only items from the input keyed ranger that match the predicate function.

func MapKeys added in v1.23.0

func MapKeys[K comparable, V any](input map[K]V) []K

MapKeys returns a slice of all keys for the map.

func MapValues added in v1.23.0

func MapValues[K comparable, V any](input map[K]V) []V

MapValues returns a slice of all values for the map.

func Must

func Must[T any](t T) T

Must panics if given value is equal to the zero value of the type.

func MustBool added in v1.35.0

func MustBool[T any](value T) bool

MustBool returns the bool representation of the given value and panics if it cannot.

func MustDuration added in v1.35.0

func MustDuration[T any](value T) time.Duration

MustDuration returns the time.Duration representation of the given value and panics if it cannot.

func MustE

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

MustE panics if the given func returns an error for the value returned is equal to the zero value of the type.

func MustInt added in v1.35.0

func MustInt[T any](value T) int

MustInt returns the int representation of the given value and panics if it cannot.

func MustMapAny added in v1.38.0

func MustMapAny[T any](value T) map[string]any

MustMapAny returns the map[string]any of the given value and panics if it cannot.

func MustMapString added in v1.38.0

func MustMapString[T any](value T) map[string]string

MustMapString returns the map[string]string of the given value and panics if it cannot.

func MustString added in v1.35.0

func MustString[T any](value T) string

MustString returns the string representation of the given value and panics if it cannot.

func MustT added in v1.14.0

func MustT[T any](v any) T

MustT panics if given 'any' value cannot be aliased to the type t.

func OptionApply

func OptionApply[T any](t T, options ...Option[T]) (T, error)

OptionApply applies all functional options to type t and returns the error if any fail to apply.

func Pointer

func Pointer[T any](t T) *T

Pointer returns a pointer to the given value.

func SliceFilter

func SliceFilter[T any](input []T, predicate Predicate[T]) []T

SliceFilter will return a new slice containing only items from the given input that match the predicate function.

func SliceFilterRange

func SliceFilterRange[T any](input Ranger[T], predicate Predicate[T]) []T

SliceFilterRange will return a new slice containing only items from the given input ranger that match the predicate function.

func SliceFlatten

func SliceFlatten[T any](input ...[]T) []T

SliceFlatten will flatten a slice of slices into a single slice.

func SliceMap added in v1.24.0

func SliceMap[TIn any, TOut any](input []TIn, mapper Mapper[TIn, TOut]) []TOut

SliceMap returns a slice with the results from the given 'map' function.

func SliceSet added in v1.39.0

func SliceSet[T comparable](input []T) map[T]struct{}

SliceSet returns a set from the given slice.

func SliceToMap

func SliceToMap[K comparable, V any](input []V, key func(v V) K) map[K]V

SliceToMap returns a map from the given slice and key function.

func SliceTypeAssert added in v1.7.0

func SliceTypeAssert[TIn any, TOut any](input []TIn) []TOut

SliceTypeAssert takes a slice of one type and asserts individual items to the other.

func TitleCase

func TitleCase(s string) string

TitleCase returns the given string in title case per English language rules.

Ref: https://en.wikipedia.org/wiki/Title_case

func ToBool added in v1.36.0

func ToBool[T any](value T) (bool, error)

ToBool returns the bool representation of the given value and errors if it cannot.

func ToDuration added in v1.36.0

func ToDuration[T any](value T) (time.Duration, error)

ToDuration returns the time.Duration representation of the given value and errors if it cannot.

func ToInt added in v1.36.0

func ToInt[T any](value T) (int, error)

ToInt returns the int representation of the given value and errors if it cannot.

func ToMapAny added in v1.38.0

func ToMapAny[T any](value T) (map[string]any, error)

ToMapAny returns the map[string]any representation of the given value and errors if it cannot.

func ToMapString added in v1.38.0

func ToMapString[T any](value T) (map[string]string, error)

ToMapString returns the map[string]any representation of the given value and errors if it cannot.

func ToString added in v1.36.0

func ToString[T any](value T) (string, error)

ToString returns the string representation of the given value and errors if it cannot.

func URLPort

func URLPort(u *url.URL) (int, error)

URLPort returns a port number for the given URL.

If a port was not defined during URL creation, an attempt is made to derive it from the scheme.

Types

type Bitmask

type Bitmask uint8

Bitmask is a `uint8` with helper methods for bitwise operations.

const (
	// ErrorNamespaceDefault is the default namespace for errors generated by this package.
	ErrorNamespaceDefault = "com.github.ahawker.stdlib"
	// ErrorFlagUnknown is set to represent unknown/unregistered errors.
	ErrorFlagUnknown Bitmask = 1 << iota
	// ErrorFlagRetryable is set to represent errors that can be retried.
	ErrorFlagRetryable
	// ErrorFlagTimeout is set to represent errors indicating a timeout occurred.
	ErrorFlagTimeout
)

func ParseBitmask

func ParseBitmask(binary string) (Bitmask, error)

ParseBitmask creates a new Bitmask from a binary string.

func (Bitmask) Clear

func (b Bitmask) Clear(bits Bitmask) Bitmask

Clear given bits from the current mask and return a new copy.

func (Bitmask) Has

func (b Bitmask) Has(bits Bitmask) bool

Has checks if bits are set.

func (Bitmask) MarshalText

func (b Bitmask) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (Bitmask) Set

func (b Bitmask) Set(bits Bitmask) Bitmask

Set bits in the current mask and return a new copy.

func (Bitmask) String

func (b Bitmask) String() string

String returns the Bitmask in binary string (001101010) form.

func (Bitmask) Toggle

func (b Bitmask) Toggle(bits Bitmask) Bitmask

Toggle bits on/off and return a new copy.

type Builder added in v1.17.0

type Builder[T any] func(t T) (T, error)

Builder defines functional builder for type t.

type Causer

type Causer interface {
	Cause() error
}

Causer defines types that return the underlying cause of an error.

type ContextKey added in v1.10.0

type ContextKey[T any] struct {
	// contains filtered or unexported fields
}

ContextKey is a generic key type associated with a specific value type. This should be used with non-exported Go types to avoid potential key collisions within the context object.

func NewContextKey added in v1.10.0

func NewContextKey[T any](name string, def T) ContextKey[T]

NewContextKey creates a new context key for a generic type.

func (ContextKey[T]) String added in v1.10.0

func (k ContextKey[T]) String() string

String returns the name of the key.

func (ContextKey[T]) Value added in v1.10.0

func (k ContextKey[T]) Value(ctx context.Context) T

Value returns the value in the context associated with this key. If the value is not present, it returns the default value.

func (ContextKey[T]) ValueOk added in v1.10.0

func (k ContextKey[T]) ValueOk(ctx context.Context) (T, bool)

ValueOk returns the value in the context associated with this key and also reports whether it was present. If the value is not present, it returns the default value.

func (ContextKey[T]) WithValue added in v1.10.0

func (k ContextKey[T]) WithValue(parent context.Context, value T) context.Context

WithValue returns a copy of parent in which the value associated with key is value.

It is a type-safe equivalent of context.WithValue.

type DebugExtras

type DebugExtras struct {
	// StackTrace of the error.
	StackTrace string `json:"stack_trace,omitempty"`
}

DebugExtras contains helpful information for debugging the error.

func (DebugExtras) IsZero

func (e DebugExtras) IsZero() bool

IsZero returns true if the Extras object is the zero/empty struct value.

type Error

type Error struct {
	// Code is a machine-readable representation for the error.
	Code string `json:"code"`
	// Extras is an optional struct to store execution context
	// that is helpful for understanding the error.
	Extras ErrorExtras `json:"extras,omitempty"`
	// Flags is a bitmask that contains additional classification/context
	// for the error, e.g. indicating if the error can be retried.
	Flags Bitmask `json:"flags,omitempty"`
	// Message is a human-readable representation for the error.
	Message string `json:"message"`
	// Namespace is a machine-readable representation for a bucketing/grouping
	// concept of errors. This is commonly used to indicate the package/repository/service
	// an error originated from.
	Namespace string `json:"namespace"`
	// Wrapped is a wrapped error if this was created from another via `Wrap`. This
	// is hidden from human consumers and only visible to machine/operators.
	Wrapped error `json:"-"`
}

Error defines a standard application error primitive.

TODO(ahawker) Add Format interface (for pretty strings) TODO(ahawker) Namespace field? Embed in the code?

func (Error) AsGroup

func (e Error) AsGroup() *ErrorGroup

AsGroup returns a *ErrorGroup containing this error and all wrapped errors it contains.

func (Error) Copy

func (e Error) Copy() Error

Copy returns a full copy of this Error, including copies of all wrapped errors within.

func (Error) Equal

func (e Error) Equal(e2 Error) bool

Equal returns true if the two Error values are equal.

func (Error) Error

func (e Error) Error() string

Error returns the string representation of the Error.

Interface: error.

func (Error) Format

func (e Error) Format(s fmt.State, verb rune)

Format returns a complex string representation of the Error for the given verbs.

Interface: fmt.Formatter.

func (Error) Is

func (e Error) Is(target error) bool

Is implements error equality checking.

Interface: HasIs.

func (Error) IsRetryable

func (e Error) IsRetryable() bool

IsRetryable returns true if the error indicates the failed operation is safe to retry.

func (Error) IsTimeout

func (e Error) IsTimeout() bool

IsTimeout returns true if the error indicates an operation timeout.

func (Error) IsTransient

func (e Error) IsTransient() bool

IsTransient returns true if the error indicates the operation failure is transient and a result might be different if tried at another time.

func (Error) IsZero

func (e Error) IsZero() bool

IsZero returns true if the Error is an empty/zero value.

func (Error) Key added in v1.26.0

func (e Error) Key() string

Key returns a value that uniquely identifies the type of error.

func (Error) String

func (e Error) String() string

String returns the Error string representation.

Interface: fmt.Stringer.

func (Error) Unwrap

func (e Error) Unwrap() error

Unwrap implements error unwrapping for nested errors.

Interface: Unwrap.

func (Error) WithDebugInfo

func (e Error) WithDebugInfo(extras DebugExtras) Error

WithDebugInfo returns a new copy of the Error with the given debug info added.

func (Error) WithFlag

func (e Error) WithFlag(attribute Bitmask) Error

WithFlag returns a new copy of the Error with the given attribute applied.

func (Error) WithHelp

func (e Error) WithHelp(extras HelpExtras) Error

WithHelp returns a new copy of the Error with the given help info added.

func (Error) WithRetry

func (e Error) WithRetry(extras RetryExtras) Error

WithRetry returns a new copy of the Error with the given retry info added.

func (Error) WithTag added in v1.31.0

func (e Error) WithTag(tags ...string) Error

WithTag returns a new copy of the Error with the given tags added.

func (Error) Wrap

func (e Error) Wrap(err error) Error

Wrap returns a new Error with the given err wrapped.

If the given err is also an Error and the current instance is a zero value, just return a copy of the given Error. This allows us to avoid checking this case at every call-site; we can just Wrap the error and handle it.

func (Error) Wrapf

func (e Error) Wrapf(format string, a ...any) Error

Wrapf returns a new Error with an error created by the given format + args.

type ErrorExtras

type ErrorExtras struct {
	// Debug information captured from the error.
	Debug DebugExtras `json:"debug,omitempty"`
	// Help information to inform operators about the error.
	Help HelpExtras `json:"help,omitempty"`
	// Retry information regarding the failed operation.
	Retry RetryExtras `json:"retry,omitempty"`
	// Tags are additional labels that can be used to categorize errors.
	Tags []string `json:"tags,omitempty"`
}

ErrorExtras contains common additional info attached to errors.

func (ErrorExtras) IsZero

func (e ErrorExtras) IsZero() bool

IsZero returns true if the ErrorExtras object is the zero/empty struct value.

func (ErrorExtras) WithDebugExtras

func (e ErrorExtras) WithDebugExtras(extras DebugExtras) ErrorExtras

WithDebugExtras returns a new copy of the ErrorExtras with the given debug info set.

func (ErrorExtras) WithHelpExtras

func (e ErrorExtras) WithHelpExtras(extras HelpExtras) ErrorExtras

WithHelpExtras returns a new copy of the ErrorExtras with the given help info set.

func (ErrorExtras) WithRetryExtras

func (e ErrorExtras) WithRetryExtras(extras RetryExtras) ErrorExtras

WithRetryExtras returns a new copy of the ErrorExtras with the given retry info set.

func (ErrorExtras) WithTag added in v1.31.0

func (e ErrorExtras) WithTag(tags ...string) ErrorExtras

WithTag returns a new copy of the ErrorExtras with the given tags set.

type ErrorGroup

type ErrorGroup struct {
	// Errors in the group.
	Errors []Error `json:"errors"`
	// Formatter to convert error group to string representation.
	Formatter ErrorGroupFormatter `json:"-"`
}

ErrorGroup stores multiple Error instances.

TODO(ahawker) Flatten JSON output to a single error when group only has one.

func ErrorJoin added in v1.7.0

func ErrorJoin(err error, errs ...error) *ErrorGroup

ErrorJoin is a helper function that will append more errors onto an ErrorGroup.

If err is not already an ErrorGroup, then it will be turned into one. If any of the errs are ErrorGroup, they will be flattened one level into err. Any nil errors within errs will be ignored. If err is nil, a new *ErrorGroup will be returned containing the given errs.

func NewErrorGroup added in v1.12.0

func NewErrorGroup(errs ...error) *ErrorGroup

NewErrorGroup creates a new *ErrorGroup with sane defaults.

func NewTranslatedErrorGroup added in v1.22.0

func NewTranslatedErrorGroup(translate ErrorTranslate, errs ...error) *ErrorGroup

NewTranslatedErrorGroup creates a new *ErrorGroup with sane defaults and translated errors.

func (*ErrorGroup) Append

func (g *ErrorGroup) Append(errs ...error)

Append adds a new error to the group.

If the given error is not an Error instance, it will be wrapped with ErrUndefined.

func (*ErrorGroup) Empty

func (g *ErrorGroup) Empty() bool

Empty will return true if the group is empty.

func (*ErrorGroup) Error

func (g *ErrorGroup) Error() string

Error string value of the ErrorGroup struct.

Interface: error.

func (*ErrorGroup) ErrorOrNil

func (g *ErrorGroup) ErrorOrNil() error

ErrorOrNil returns an error interface if this Error represents a list of errors, or returns nil if the list of errors is empty. This function is useful at the end of accumulation to make sure that the value returned represents the existence of errors.

func (*ErrorGroup) GroupOrNil

func (g *ErrorGroup) GroupOrNil() *ErrorGroup

GroupOrNil returns the ErrorGroup interface if this group represents contains one or more errors. If it's empty, nil is returned.

func (*ErrorGroup) Len

func (g *ErrorGroup) Len() int

Len returns the number of errors in the group.

Interface: sort.Interface.

func (*ErrorGroup) Less

func (g *ErrorGroup) Less(i, j int) bool

Less determines order for sorting a group.

Interface: sort.Interface.

func (*ErrorGroup) Slice

func (g *ErrorGroup) Slice() []Error

Slice returns a slice of all errors in the group.

func (*ErrorGroup) Swap

func (g *ErrorGroup) Swap(i, j int)

Swap moves errors in the group during sorting.

Interface: sort.Interface.

func (*ErrorGroup) Translate added in v1.21.0

func (g *ErrorGroup) Translate(translate ErrorTranslate)

Translate performs an in-place translation of errors in the group for swapping context.

func (*ErrorGroup) Unwrap

func (g *ErrorGroup) Unwrap() error

Unwrap returns the next error in the group or nil if there are no more errors.

Interface: errors.Unwrap, HasUnwrap.

type ErrorGroupFormatter

type ErrorGroupFormatter func([]Error) string

ErrorGroupFormatter is a function callback that is called by ErrorGroup to turn the list of errors into a string.

type ErrorTranslate

type ErrorTranslate func(err error) error

ErrorTranslate defines function that can translate errors between two different contexts.

This is commonly used to convert between domain and adapter error types.

type HasAs

type HasAs interface {
	As(target any) bool
}

HasAs defines types necessary for stdlib `errors.As` support.

type HasIs

type HasIs interface {
	Is(target error) bool
}

HasIs defines types necessary for stdlib `errors.Is` support.

type HasUnwrap

type HasUnwrap interface {
	Unwrap() error
}

HasUnwrap defines types necessary for stdlib `errors.Unwrap` support.

type HelpExtras

type HelpExtras struct {
	// Links to help documentation regarding the error.
	Links []Link `json:"links,omitempty"`
}

HelpExtras contains helpful hyperlinks for the error.

func (HelpExtras) IsZero

func (e HelpExtras) IsZero() bool

IsZero returns true if the Extras object is the zero/empty struct value.

type KeyedMapper added in v1.24.0

type KeyedMapper[K comparable, VIn any, VOut any] func(k K, v VIn) VOut

KeyedMapper describes a 'map' function for a given key/value input.

type KeyedPredicate

type KeyedPredicate[K comparable, V any] func(k K, v V) bool

KeyedPredicate describes functions which return true/false based on a given key/value input.

type KeyedRanger

type KeyedRanger[K comparable, V any] interface {
	// Range calls the given function for all items available for iteration.
	//
	// If Range returns `false`, iteration will stop.
	Range(predicate KeyedPredicate[K, V])
}

KeyedRanger describes types that export a `Range` method for iteration over key/value collections.

type Link struct {
	URL         string
	Description string
}

Link contains a description and hyperlink.

type Mapper added in v1.24.0

type Mapper[TIn any, TOut any] func(t TIn) TOut

Mapper describes a 'map' function applied to another type.

type Memoize

type Memoize[T any] struct {
	// Fn is called once and its result/error is cached.
	Fn func() (T, error)
	// contains filtered or unexported fields
}

Memoize is a simple struct that wraps a `sync.Once` to provide thread safe memoized results for costly computation.

func (*Memoize[T]) Get

func (m *Memoize[T]) Get() (T, error)

Get returns the value + error from the

type Option

type Option[T any] func(t T) error

Option defines functional options for type t.

type Optional added in v1.34.0

type Optional[T any] struct {
	// contains filtered or unexported fields
}

Optional wraps a value of type `T` tracks a default value and whether it changed.

func Default added in v1.34.0

func Default[T any](v T) *Optional[T]

Default creates an Optional with an empty value and distinct default value.

func Some added in v1.34.0

func Some[T any](v T) *Optional[T]

Some creates an Optional with a value.

func (*Optional[T]) Changed added in v1.34.0

func (o *Optional[T]) Changed() bool

Changed returns true if the value has been set.

func (*Optional[T]) Get added in v1.34.0

func (o *Optional[T]) Get() T

Get returns the value if it has been set, otherwise the default value.

func (*Optional[T]) Set added in v1.34.0

func (o *Optional[T]) Set(v T)

Set sets the value and marks it as changed.

type Predicate

type Predicate[T any] func(t T) bool

Predicate describes functions which return true/false based on a given input.

type Ranger

type Ranger[T any] interface {
	// Range calls the given function for all items available for iteration.
	//
	// If Range returns `false`, iteration will stop.
	Range(predicate Predicate[T])
}

Ranger describes types that export a `Range` method for iteration over single item collections.

type RetryExtras

type RetryExtras struct {
	// Delay duration abide by before retrying the failed operation.
	Delay time.Duration
}

RetryExtras contains helpful information for dictating how/why retries can/should happen.

func (RetryExtras) IsZero

func (e RetryExtras) IsZero() bool

IsZero returns true if the Extras object is the zero/empty struct value.

type Valid added in v1.13.0

type Valid[T any] struct {
	// Value of type T which has been validated.
	Value T
}

Valid is a struct that wraps an arbitrary value to indicate that it is valid and has passed all checks.

func ValidCheck added in v1.13.0

func ValidCheck[T any](t T, validators ...Validator[T]) (*Valid[T], error)

ValidCheck applies all functional validators to type t and returns the error if any fail to apply.

If all return successfully, a Valid[T] is returned.

type Validator added in v1.13.0

type Validator[T any] func(t T) error

Validator defines functional validator for type t.

type Zeroer

type Zeroer interface {
	// IsZero returns true if the value of the instance is equal
	// to the "zero" value of the type.
	IsZero() bool
}

Zeroer describes types that support `IsZero` checks.

Jump to

Keyboard shortcuts

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