errctx

package
v0.104.0 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2024 License: Apache-2.0 Imports: 4 Imported by: 0

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

func ValueFrom(err error, key string) (any, bool)

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

func WithValue(err error, key string, val any) error

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)

func WithValues

func WithValues(err error, kvs map[string]any) error

WithValues attaches multiple key value pairs. The behavior is similar to WithValue.

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.

Jump to

Keyboard shortcuts

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