Documentation ¶
Index ¶
- Variables
- func Adapt(err error, guard MetaError) error
- func AllAttrs() map[string]any
- func AllMetaErrors() map[metaID]MetaError
- func AppName() string
- func As(err error, target interface{}) bool
- func Cause(err error) error
- func Get(m error, key any) any
- func GetAll(m error, key any) []any
- func GetAllErrors(err error) []error
- func GetApp(err error) string
- func GetCode(err error) string
- func GetMessage(err error) string
- func GetSource(err error) string
- func Is(err, target error) bool
- func IsCauseOrLatestMetaError(err, target error) bool
- func Map(err error) map[string]any
- func MetaID(app, source, code string) string
- func NewAttrKey(name string) any
- func RegisterMetaError(me MetaError) error
- func SetAppName(appNew string) error
- func SetFormatMode(mode FormatMode)
- func Unwrap(err error) error
- func With(err error, opts ...Option) error
- func WithErrorOptions(err, optsErr error) error
- func WithMessagef(err error, format string, args ...any) error
- func WithStack(err error) error
- func WithValue(err error, key, val any) error
- func Wrap(err error, message string) error
- func Wrapf(err error, format string, args ...interface{}) error
- type Adapter
- type AdapterOption
- type Attr
- func (a *Attr[T]) Description() string
- func (a *Attr[T]) Get(err error) T
- func (a *Attr[T]) GetAll(err error) []T
- func (a *Attr[T]) GetAny(err error) any
- func (a *Attr[T]) Key() any
- func (a *Attr[T]) MarshalJSON() ([]byte, error)
- func (a *Attr[T]) Name() string
- func (a *Attr[T]) Option(value T) Option
- func (a *Attr[T]) With(err error, value T) error
- type AttrInterface
- type AttrOption
- type AttrOptions
- type Attrs
- type Error
- type FormatMode
- type Meta
- type MetaError
- type Option
Constants ¶
This section is empty.
Variables ¶
var ( // ErrorAttr used to attach another error on input error, usually used to attach meta error ErrorAttr = NewAttr[error]("error", WithAttrDescription("error as an attr")) // CtxAttr used to attach context.Context on error CtxAttr = NewAttr[context.Context]("ctx", WithAttrDescription("context.Context as an attr")) // Meta used to attach meta to Error MetaAttr = NewAttr[*Meta]("meta", WithAttrDescription("meta as an attr")) // Message used to attach message to Error MessageAttr = NewAttr[string]("msg", WithAttrDescription("message as an attr")) // Status used as meta value stands for http status, // Status.Get returns http status if err is MetaError with status attached, // otherwise return 500 if err != nil else return 200 StatusAttr = NewAttr[int]("status", WithAttrDefault(func(err error) any { if err != nil { return http.StatusInternalServerError } return http.StatusOK }), WithAttrDescription("http status as an attr")) // Caller used as meta value stands for runtime.Caller info CallerAttr = NewAttr[string]("caller", WithAttrDescription("caller as an attr")) // Stack attach `github.com/pkg/errors.stack` on error StackAttr = NewAttr[*stack]("stack", WithAttrDescription("github.com/pkg/errors.stack as an attr")) )
var ( OK = NewMetaError(source, "success(0)", "success", status(http.StatusOK)) Canceled = NewMetaError(source, "canceled(1)", "client cancelled request", status(499)) Unknown = NewMetaError(source, "unknown(2)", "server throws an exception", status(http.StatusInternalServerError)) InvalidArgument = NewMetaError(source, "invalid_argument(3)", "invalid argument", status(http.StatusBadRequest)) DeadlineExceeded = NewMetaError(source, "deadline_exceeded(4)", "timeout", status(http.StatusGatewayTimeout)) NotFound = NewMetaError(source, "not_found(5)", "not found", status(http.StatusNotFound)) AlreadyExists = NewMetaError(source, "already_exists(6)", "already exists", status(http.StatusConflict)) PermissionDenied = NewMetaError(source, "permission_denied(7)", "permission denied", status(http.StatusForbidden)) ResourceExhausted = NewMetaError(source, "resource_exhausted(8)", "resource exhauste", status(http.StatusTooManyRequests)) FailedPrecondition = NewMetaError(source, "failed_precondition(9)", "failed precondition", status(http.StatusBadRequest)) Aborted = NewMetaError(source, "aborted(10)", "operation was aborted", status(http.StatusConflict)) OutOfRange = NewMetaError(source, "out_of_range(11)", "operation was attempted past the valid range", status(http.StatusBadRequest)) Unimplemented = NewMetaError(source, "unimplemented(12)", "unimplemented", status(http.StatusNotImplemented)) Internal = NewMetaError(source, "internal(13)", "internal error", status(http.StatusInternalServerError)) DataLoss = NewMetaError(source, "data_loss(15)", "unrecoverable data loss or corruption", status(http.StatusInternalServerError)) Unauthenticated = NewMetaError(source, "unauthenticated(16)", "unauthenticated", status(http.StatusForbidden)) )
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`
var ( // New is `errors.New` New = errors.New // Errorf is `fmt.Errorf` Errorf = fmt.Errorf )
standard
var ( MetaAttrAppFieldName string = "meta.app" MetaAttrSourceFieldName string = "meta.source" MetaAttrCodeFieldName string = "meta.code" MetaAttrMessageFieldName string = "meta.message" )
var ( WithError = ErrorAttr.With ErrorOption = ErrorAttr.Option WithMeta = MetaAttr.With MetaOption = MetaAttr.Option WithCtx = CtxAttr.With CtxOption = CtxAttr.Option WithStatus = StatusAttr.With StatusOption = StatusAttr.Option WithCaller = CallerAttr.With CallerOption = CallerAttr.Option StackOption = StackAttr.Option MessageOption = MessageAttr.Option )
helper functions for attrs
var ( // WithMessage imitate `github.com/pkg/errors.WithMessage` but implemented with `Message` attr WithMessage = MessageAttr.With )
github.com/pkg/errros
Functions ¶
func AllMetaErrors ¶
func AllMetaErrors() map[metaID]MetaError
AllMetaErrors return all registered MetaErrors as a map with key is `app:source:code`
func AppName ¶
func AppName() string
AppName return current app name, use `SetAppName` or `inithook.AppName` to set app name
func As ¶
As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.
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.
As will panic if target is not a non-nil pointer to either a type that implements error, or to any interface type. As returns false if err is nil.
func Cause ¶
Cause returns the underlying cause of the error, if possible. An error value has a cause if it implements the following interface:
type unwrap interface { Unwrap() error }
If the error does not implement unwrap, the original error will be returned. If the error is nil, nil will be returned without further investigation.
func GetAllErrors ¶
GetAllErrors get all errors contained in err, all errors attached by `WithError` + Cause
func GetCode ¶
GetCode returns error code if err is ContextError, otherwise return Unknown.Code() if err != nil else return Ok.Code()
func GetMessage ¶
GetMessage returns error message if err is ContextError, otherwise return Unknown.Message() if err != nil else return Ok.Message()
func GetSource ¶
GetSource returns error source if err is ContextError, otherwise return empty string
func Is ¶
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.
func IsCauseOrLatestMetaError ¶
IsCauseOrLatest used to test if err is a error, return true only if target == Cause(err) || target == GetLatestMetaError(err)
func Map ¶
Map unwrap all to get `name:value` map of all attrs
NOTE: 1. unlike Get or `GetAll`, Map do not traversal the value of `valueError` 2. result will not contain the value if key type is not *string 3. if meta exists, then app, source and message fields will be added into result 4. if key's name duplicates, the result will only contains the latest value
func NewAttrKey ¶
NewAttrKey used to creates a new Attr's internal key https://github.com/golang/go/issues/33742
func RegisterMetaError ¶
RegisterMetaError register MetaError into metaErrors registry, return error is exists
func SetAppName ¶
SetAppName set app name and register Meta to new app namespace
func SetFormatMode ¶
func SetFormatMode(mode FormatMode)
SetFormatMode set mode for formatting the `valueError`
func Unwrap ¶
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 WithMessagef ¶
WithMessage imitate `github.com/pkg/errors.WithMessagef` but implemented with `Message` attr
func WithStack ¶
WithStack imitate `github.com/pkg/errors.WithStack` but implemented with `Stack` attr
func WithValue ¶
WithValue returns a copy of parent in which the value associated with key is val.
The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using meta. Users of WithValue should define their own types for keys. To avoid allocating when assigning to an interface{}, context keys often have concrete type struct{}. Alternatively, exported context key variables' static type should be a pointer or interface.
Types ¶
type Adapter ¶
Adapter provides `Adapt` mainly to support suggestive error, error delivery path, error overrides ...
func NewAdapter ¶
func NewAdapter(opts ...AdapterOption) Adapter
NewAdapter creates a new Adapter, usually no need to create a new one, just use the default `Adapt` function is enough
type AdapterOption ¶
type AdapterOption func(*adapter)
AdapterOption default adapter implementation control option
func WithAddCaller ¶
func WithAddCaller() AdapterOption
WithAddCaller add caller for default adapter implementation
func WithCallerFunc ¶
func WithCallerFunc(fn func(int) string) AdapterOption
WithCallerFunc specify the caller func which returns the caller info for default adapter implementation
func WithCallerSkip ¶
func WithCallerSkip(skip int) AdapterOption
WithCallerSkip specify caller skip depth for default adapter implementation
func WithDefaultOptions ¶
func WithDefaultOptions(opts ...Option) AdapterOption
WithDefaultOptions specify the default meta options to append when `Adapt` for default adapter implementation
func WithMetaMappingFunc ¶
func WithMetaMappingFunc(fn func(*Meta) MetaError) AdapterOption
WithMetaMappingFunc specify the default meta mappping function
type Attr ¶
type Attr[T any] struct { // contains filtered or unexported fields }
Attr defines an value extension for `Meta`, it can create an MetaOption by `With` method and get the value by `Get` method
Usage:
// define a new Attr var Status = NewAttr[int](WithAttrDefault(func(err error){ if err != nil { return http.StatusInternalServerError } return http.StatusOK })) // use `Attr.With` var NotFound = NewMetaError("not_found(5)", "not found", source, Status.With(http.StatusNotFound)) // use `Attr.Get` log.Println(Status.Get(err))
func GetAttrByKey ¶
GetAttrByKey get attr by type and key from attrs registry
func GetAttrByName ¶
GetAttrByName get attr by type and name from attrs registry NOTE: the result may not be what you want, since the same name is allowed to be overwritten by default.
func MustGetAttrByKey ¶
MustGetAttrByKey get attr by key, panic if not found
func MustGetAttrByName ¶
MustGetAttrByKey get attr by name, panic if not found
func NewAttr ¶
func NewAttr[T any](name string, opts ...AttrOption) *Attr[T]
NewAttr creates a new `Attr`
func (*Attr[T]) Description ¶
Description returns the description of Attr
func (*Attr[T]) Get ¶
Get get value specified by Attr's internal key from error if implement MetaError, otherwise return default value
func (*Attr[T]) MarshalJSON ¶
type AttrInterface ¶
AttrInterface abstract Attr's minimal interface used for `Attrs`
type AttrOption ¶
type AttrOption func(*AttrOptions)
AttrOption defines `Attr` constructor option
func WithAttrDefault ¶
func WithAttrDefault(fn func(error) any) AttrOption
WithAttrDefault specify `Attr` default value function
func WithAttrDescription ¶
func WithAttrDescription(desc string) AttrOption
WithAttrDefault specify `Attr` description
func WithAttrDoNotRegister ¶
func WithAttrDoNotRegister(noReg bool) AttrOption
WithAttrDoNotRegister specify `Attr` DoNotRegister
func WithAttrPanicOnDuplicateNames ¶
func WithAttrPanicOnDuplicateNames(noPanic bool) AttrOption
WithAttrPanicOnDuplicateNames specify `Attr` PanicOnDuplicateNames
type AttrOptions ¶
type AttrOptions struct { // DefaultValueFunc Attr's default value function DefaultValueFunc func(error) any // Description Attr's description Description string // DoNotRegister do not register the new created attr into registry, default to false DoNotRegister bool // PanicOnDuplicateNames duplicate names are allowed by default PanicOnDuplicateNames bool }
AttrOptions defines `Attr` constructor options
type Attrs ¶
type Attrs []AttrInterface
Attrs is a group of AttrInterface, which usually used to extractor attrs's values
type FormatMode ¶
type FormatMode int
FormatMode used to format Meta value wrapper
const ( // Default format value meta as `meta.String():key=value` Default FormatMode = iota // Simplified format value meta as `meta.String():*=*` Simplified // Default format value meta as `meta.String():key=*` NoValue )
type Meta ¶
type Meta struct {
// contains filtered or unexported fields
}
func (*Meta) MarshalJSON ¶
type MetaError ¶
func GetLatestMetaError ¶
GetLatestMetaError return the latest MetaError in err, returns nil if not found
func GetMetaError ¶
GetMetaError get Meta according to app, source and code
func NewMetaError ¶
NewMetaError define a new error with meta attached