modulepackage
0.0.0-20230122034905-509c1e454d9b
Repository: https://github.com/ccmonky/errors.git
Documentation: pkg.go.dev
# README
errors
like pkg/errors, but can wrap and retrieve anything
Requirements
Usage
- error definition
var source = "your_package_path"
var NotFound = NewMetaError(source, "not_found(5)", "not found", status(http.StatusNotFound))
- error override
import "github.com/ccmonky/errors"
errors.NotFound = errors.With(errors.NotFound, errors.StatusOption(400), ...)
- error(meta) suggestion
err := errors.New("xxx")
err = errors.WithError(err, errors.NotFound)
- error(meta) fallback
// NOTE: do notknow whether error has carried meta
err = errors.Adapt(err, errors.Unknown)
- error enforce
// NOTE: attach errors.Unavailable on err whether err has carried meta or not
err = errors.WithError(err, errors.Unavailable)
- error attr
// define attr
CountAttr := errors.NewAttr[int]("count", errors.WithAttrDescription("xxx count as an attr"))
// use attr
err = CountAttr.With(errors.New("xxx"), 100)
// or
err = errors.With(errors.New("xxx"), CountAttr.Option(100))
// get count
count := CountAttr.Get(err)
count == 100 // true
- error wrap
err := errors.New("xxx")
err = errors.WithError(err, errors.NotFound)
err = errors.WithMessage(err, "wrapper")
err = errors.WithCaller(err, "caller...")
err = errors.WithSatus(err, 206)
//...
- error unwrap
// unwrap error
originErr := errors.New("xxx")
err := Cause(errors.With(err, errors.ErrorOption(errors.NotFound), errors.StatusOption(409), errors.CallerOption("caller...")))
log.Print(originErr == err) // true
// unwrap attr
errors.StatusAttr.Get(err) == 409
errors.ErrorAttr.Get(err) == errors.NotFound
// NOTE: you can also get attr in attr's value(as long as it implement `interface{ Value(any)any}`, like this
errors.MetaAttr.Get(err).Code() == "not_found(5)"
- error assert
originErr := errors.New("xxx")
err := errors.WithError(originErr, errors.NotFound)
err = errors.WithMessage(err, "xxx")
errors.Is(err, originErr) // true
errors.Is(err, errors.NotFound) // true
errors.Is(err, errors.AlreadyExists) // false
errors.IsCauseOrLatestMetaError(err, originErr) // true
errors.IsCauseOrLatestMetaError(err, errors.NotFound) // true
errors.IsCauseOrLatestMetaError(err, errors.AlreadyExists) // false
err = errors.WithError(err, errors.AlreadyExists)
errors.Is(err, originErr) // true
errors.Is(err, errors.NotFound) // true
errors.Is(err, errors.AlreadyExists) // true
errors.IsCauseOrLatestMetaError(err, originErr) // true
errors.IsCauseOrLatestMetaError(err, errors.NotFound) // false
errors.IsCauseOrLatestMetaError(err, errors.AlreadyExists) // true
err = errors.Adapt(err, errors.Unknown)
errors.Is(err, originErr) // true
errors.Is(err, errors.NotFound) // true
errors.Is(err, errors.AlreadyExists) // true
errors.Is(err, errors.Unknown) // false
errors.IsCauseOrLatestMetaError(err, originErr) // true
errors.IsCauseOrLatestMetaError(err, errors.NotFound) // false
errors.IsCauseOrLatestMetaError(err, errors.AlreadyExists) // true
errors.IsCauseOrLatestMetaError(err, errors.Unknown) // false
- error collection
err := errors.WithError(errors.New("e1"), errors.New("e2"))
err = errors.WithError(err, errors.New("e3"))
log.Println(errors.GetAllErrors(err))
// Output: [e1 e2 e3]
- error attr extraction
err := errors.WithError(errors.New("xxx"), errors.NotFound)
err = errors.WithMessage(err, "wrapper1")
err = errors.WithCaller(err, "caller1")
err = errors.WithError(err, errors.AlreadyExists)
err = errors.WithMessage(err, "wrapper2")
err = errors.WithCaller(err, "caller2")
var ki int
err = errors.WithValue(err, &ki, "will not in map")
var ks = "ks"
err = errors.WithValue(err, &ks, "ks")
// errors.Map(err): get all values
// NOTE: error and *Meta will be flatten
m := errors.Map(err)
assert.Equalf(t, 10, len(m), "m length")
assert.Equalf(t, "myapp", m["meta.app"], "meta.app")
assert.Equalf(t, "github.com/ccmonky/errors", m["meta.source"], "meta.source")
assert.Equalf(t, "already_exists(6)", m["meta.code"], "meta.code")
assert.Equalf(t, "already exists", m["meta.message"], "meta.message")
assert.Equalf(t, "ks", m["ks"], "ks")
assert.Equalf(t, "wrapper2", m["msg"], "msg")
assert.Equalf(t, "caller2", m["caller"], "caller")
assert.Equalf(t, 409, m["status"], "status")
assert.Equalf(t, "meta={source=errors;code=already_exists(6)}:status={409}", fmt.Sprint(m["error"]), "error")
assert.Equalf(t, "source=errors;code=already_exists(6)", fmt.Sprint(m["meta"]), "meta")
// errors.Attrs: get values of specified attrs
// NOTE: error and *Meta will be flatten
m := errors.NewAttrs(errors.ErrorAttr, errors.MessageAttr).Map(err)
assert.Equalf(t, 8, len(m), "m length")
assert.Equalf(t, "myapp", m["meta.app"], "meta.app")
assert.Equalf(t, "github.com/ccmonky/errors", m["meta.source"], "meta.source")
assert.Equalf(t, "already_exists(6)", m["meta.code"], "meta.code")
assert.Equalf(t, "already exists", m["meta.message"], "meta.message")
assert.Equalf(t, "wrapper2", m["msg"], "msg")
assert.Equalf(t, 409, m["status"], "status")
assert.Equalf(t, "meta={source=errors;code=already_exists(6)}:status={409}", fmt.Sprint(m["error"]), "error")
assert.Equalf(t, "source=errors;code=already_exists(6)", fmt.Sprint(m["meta"]), "meta")
- error admin
// list all registered meta errors(generated by `NewMetaError`)
mes, _ := errors.AllMetaErrors()
log.Println(string(data))
// list all registered error attrs(generated by `NewAttr`)
attrs, _ := errors.AllAttrs()
log.Println(string(data))
meta errors marshal result like this:
{
":github.com/ccmonky/errors:aborted(10)": {
"error": {
"key": "meta",
"value": {
"meta.app": "myapp",
"meta.code": "aborted(10)",
"meta.message": "operation was aborted",
"meta.source": "github.com/ccmonky/errors"
}
},
"key": "status",
"value": 409
},
":github.com/ccmonky/errors:already_exists(6)": {
"error": {
"key": "meta",
"value": {
"meta.app": "myapp",
"meta.code": "already_exists(6)",
"meta.message": "already exists",
"meta.source": "github.com/ccmonky/errors"
}
},
"key": "status",
"value": 409
}
// ...
}
attrs json marshal result like this:
{
"caller:0xc000110ed0": {
"description": "caller as an attr",
"has_default_value_func": false,
"name": "caller",
"type": "string"
},
"ctx:0xc000110dd0": {
"description": "context.Context as an attr",
"has_default_value_func": false,
"name": "ctx",
"type": "context.Context"
},
"error:0xc000110d70": {
"description": "error as an attr",
"has_default_value_func": false,
"name": "error",
"type": "error"
},
"meta:0xc000110e10": {
"description": "meta as an attr",
"has_default_value_func": false,
"name": "meta",
"type": "*errors.Meta"
},
"msg:0xc000110e50": {
"description": "message as an attr",
"has_default_value_func": false,
"name": "msg",
"type": "string"
},
"stack:0xc000110f10": {
"description": "github.com/pkg/errors.stack as an attr",
"has_default_value_func": false,
"name": "stack",
"type": "*errors.stack"
},
"status:0xc000110e90": {
"description": "http status as an attr",
"has_default_value_func": true,
"name": "status",
"type": "int"
}
}
# Functions
Adapt defaultAdapter's Adapt.
AllAttrs return all registered Attrs.
AllMetaErrors return all registered MetaErrors as a map with key is `app:source:code`.
AppName return current app name, use `SetAppName` or `inithook.AppName` to set app name.
As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.
Cause returns the underlying cause of the error, if possible.
Empty returns a non-nil, empty Error.
No description provided by the author
GetAll get all values of key recursively.
GetAllErrors get all errors contained in err, all errors attached by `WithError` + Cause.
GetApp get app name from error if err is ContextError, otherwise return empty string.
GetAttrByKey get attr by type and key from attrs registry.
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.
GetCode returns error code if err is ContextError, otherwise return Unknown.Code() if err != nil else return Ok.Code().
GetLatestMetaError return the latest MetaError in err, returns nil if not found.
GetMessage returns error message if err is ContextError, otherwise return Unknown.Message() if err != nil else return Ok.Message().
GetMetaError get Meta according to app, source and code.
GetSource returns error source if err is ContextError, otherwise return empty string.
Is reports whether any error in err's chain matches target.
IsCauseOrLatest used to test if err is a error, return true only if target == Cause(err) || target == GetLatestMetaError(err).
Map unwrap all to get `name:value` map of all attrs
NOTE: 1.
MetaID returns a unique id of `Meta`.
MustGetAttrByKey get attr by key, panic if not found.
MustGetAttrByKey get attr by name, panic if not found.
NewAdapter creates a new Adapter, usually no need to create a new one, just use the default `Adapt` function is enough.
NewAttr creates a new `Attr`.
NewAttrKey used to creates a new Attr's internal key https://github.com/golang/go/issues/33742.
NewAttrs create new Attrs.
NewMetaError define a new error with meta attached.
Options used to get `[]Option` attached on err.
RegisterMetaError register MetaError into metaErrors registry, return error is exists.
SetAppName set app name and register Meta to new app namespace.
SetFormatMode set mode for formatting the `valueError`.
Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error.
With used to attach multiple values on error with options.
WithAddCaller add caller for default adapter implementation.
WithAttrDefault specify `Attr` default value function.
WithAttrDefault specify `Attr` description.
WithAttrDoNotRegister specify `Attr` DoNotRegister.
WithAttrPanicOnDuplicateNames specify `Attr` PanicOnDuplicateNames.
WithCallerFunc specify the caller func which returns the caller info for default adapter implementation.
WithCallerSkip specify caller skip depth for default adapter implementation.
WithDefaultOptions specify the default meta options to append when `Adapt` for default adapter implementation.
WithErrorOptions.
WithMessage imitate `github.com/pkg/errors.WithMessagef` but implemented with `Message` attr.
WithMetaMappingFunc specify the default meta mappping function.
WithStack imitate `github.com/pkg/errors.WithStack` but implemented with `Stack` attr.
WithValue returns a copy of parent in which the value associated with key is val.
Wrap imitate `github.com/pkg/errors.Wrap` but implemented with `Message` & `Stack` attrs.
Wrapf imitate `github.com/pkg/errors.Wrapf` but implemented with `Message` & `Stack` attrs.
# Constants
Default format value meta as `meta.String():key=value`.
Default format value meta as `meta.String():key=*`.
Simplified format value meta as `meta.String():*=*`.
# Variables
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
Caller used as meta value stands for runtime.Caller info.
helper functions for attrs.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
CtxAttr used to attach context.Context on error.
helper functions for attrs.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
ErrorAttr used to attach another error on input error, usually used to attach meta error.
Errorf is `fmt.Errorf`.
helper functions for attrs.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
Message used to attach message to Error.
helper functions for attrs.
Meta used to attach meta to Error.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
helper functions for attrs.
New is `errors.New`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
Stack attach `github.com/pkg/errors.stack` on error.
helper functions for attrs.
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.
helper functions for attrs.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
refer to `https://grpc.github.io/grpc/core/md_doc_statuscodes.html`.
helper functions for attrs.
helper functions for attrs.
helper functions for attrs.
WithMessage imitate `github.com/pkg/errors.WithMessage` but implemented with `Message` attr.
helper functions for attrs.
helper functions for attrs.
# Structs
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))
*/.
AttrOptions defines `Attr` constructor options.
No description provided by the author
# Interfaces
Adapter provides `Adapt` mainly to support suggestive error, error delivery path, error overrides ...
AttrInterface abstract Attr's minimal interface used for `Attrs`.
Error is a error with context values.
No description provided by the author
# Type aliases
AdapterOption default adapter implementation control option.
AttrOption defines `Attr` constructor option.
Attrs is a group of AttrInterface, which usually used to extractor attrs's values.
FormatMode used to format Meta value wrapper.
Option used to attach value on error.