stdlib

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: May 29, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

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 E

func E[T any](v T) bool

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 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 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 Must

func Must[T any](t T) T

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

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 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](slices ...[]T) []T

SliceFlatten will flatten a slice of slices into a single 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 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 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.

func VO

func VO[T ValueObject](v T) T

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 = "github.com/ahawker/stdlibx-go"
	// 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 Causer

type Causer interface {
	Cause() error
}

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

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 Entity

type Entity interface {
	EntityID() ID
}

type Equaler

type Equaler[T any] interface {
	Equal(x T, y T) bool
}

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) 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) 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"`
}

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.

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 ErrorTranslateGroup

func ErrorTranslateGroup(translate ErrorTranslate, errors ...error) *ErrorGroup

ErrorTranslateGroup calls the given translate func for each given error to build a group.

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) 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 ID

type ID struct {
	Type  string
	Value string
}

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 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 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 ValueObject

type ValueObject interface{}

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