Documentation ¶
Overview ¶
Package errctx allow attaching values to an error in a structural way using WithValue and read the value out using ValueFrom. It is inspired by context package and works along with error wrapping introduced in go 1.13.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ValueFrom ¶
ValueFrom traverse entire error chain and returns the value from the first ErrorWithValue that contains the key. e.g. for an error created using errctx.WithValue(errctx.WithValue(base, "k", "v1"), "k", "v2") ValueFrom(err, "k") returns "v2".
func WithValue ¶
WithValue attaches a single key value pair to a non nil error. If err is nil, it does nothing and return nil. key has to be a non empty string otherwise it will panic. val can be nil, and the existence of a key with nil value can be distinguished using the bool return value in Value/ValueFrom call.
It is a good practice to define the key as a constant strange instead of inline literal.
const taskErrKey = "task" return errctx.WithValue(taskErrKey, myTask) task, ok := errctx.ValueFrom(err, taskErrKey)
Types ¶
type ErrorWithValue ¶
type ErrorWithValue interface { error // Value returns a value attached to the error by key. // If the key does not exists, it returns nil, false. // The value saved can be nil, so it can also returns nil, true // to indicates a key exists but its value is nil. // // It does NOT do recursive Value calls (like context.Context). // For getting value from entire error chain, use ValueFrom. Value(key string) (v any, ok bool) }
ErrorWithValue indicates the error has some (could be just one) key value pairs attached to it during error wrapping.