Documentation
¶
Overview ¶
Package jsonxtractr provides a tiny, stdlib-only way to attach structured metadata and sentinels to errors while staying fully composable with the Go standard library. The model is:
Each function builds an entry with New(...) passing an optional trailing cause: return doterr.New(ErrRepo, "key", val, cause) // cause last
With(...) is a flexible convenience for same-function enrichment. It can:
Enrich the rightmost doterr entry within an existing joined error, or
Join a new entry if no doterr entry exists, and
(Optionally) treat a final trailing error as the cause and join it last.
Combine([]error) bundles independent failures into a single error that unwraps to its members, preserving order.
Index ¶
- Variables
- func AppendErr(errs []error, err error) []error
- func CombineErrs(errs []error) error
- func ErrValue[T any](err error, key string) (T, bool)
- func Errors(err error) []error
- func ExtractValueFromBytes(jsonBytes []byte, selector Selector) (value any, err error)
- func ExtractValueFromReader(reader io.Reader, selector Selector) (value any, err error)
- func ExtractValuesFromBytes(jsonBytes []byte, selectors []Selector) (valuesMap ValuesMap, found []Selector, err error)
- func ExtractValuesFromReader(reader io.Reader, selectors []Selector) (valuesMap ValuesMap, notFound []Selector, err error)
- func FindErr[T error](err error) (out T, ok bool)
- func NewErr(parts ...any) error
- func WithErr(parts ...any) error
- type KV
- type Selector
- type Selectors
- type ValuesMap
Constants ¶
This section is empty.
Variables ¶
var ( ErrMissingSentinel = errors.New("missing required sentinel error") ErrTrailingKey = errors.New("trailing key without value") ErrMisplacedError = errors.New("error in wrong position") ErrInvalidArgumentType = errors.New("invalid argument type") ErrOddKeyValueCount = errors.New("odd number of key-value arguments") ErrCrossPackageError = errors.New("error from different doterr package") ErrFailedTypeAssertion = errors.New("failed type assertion") )
Sentinel errors for validation failures
var ( ErrJSONBodyCannotBeEmpty = errors.New("JSON body cannot be empty") ErrJSONIndexOutOfRange = errors.New("JSON index out of range") ErrJSONPathContainsEmptySegment = errors.New("JSON path contains empty segment") ErrJSONPathExpectedArrayAtSegment = errors.New("JSON path expected array at segment") ErrJSONPathExpectedObjectAtSegment = errors.New("JSON path expected object at segment") ErrJSONPathSegmentNotFound = errors.New("JSON path segment not found") ErrJSONPathTraversalFailed = errors.New("JSON path traversal failed") ErrJSONReadFailed = errors.New("JSON read failed") ErrJSONStreamingParseFailed = errors.New("JSON streaming parse failed") ErrJSONTokenReadFailed = errors.New("JSON token read failed") ErrJSONUnmarshalFailed = errors.New("JSON unmarshal failed") ErrJSONValueSelectorCannotBeEmpty = errors.New("JSON value selector cannot be empty") ErrJSONSelectorNotFound = errors.New("JSON selector not found") ErrExtractingFromJSONByReader = errors.New("extracting from JSON by reader") ErrExtractingFromJSONBytes = errors.New("extracting from JSON bytes") ErrExtractingJSONBodyValues = errors.New("extracting JSON body values") ErrFailedToExtractValueFromJSON = errors.New("failed to extract value from JSON") )
Sentinel errors for various jsonxtractr operations.
Functions ¶
func CombineErrs ¶
CombineErrs bundles a slice of errors into a single composite error that unwraps to its members. Order is preserved and nils are skipped. Returns nil for an empty/fully-nil slice, or the sole error when there is exactly one.
func ErrValue ¶
ErrValue extracts a single metadata value by key with type safety. Returns the value and true if found and the value is of type T. Returns the zero value of T and false if not found or type mismatch.
Example:
status, ok := doterr.ErrValue[int](err, "http_status")
if ok {
fmt.Printf("Status: %d\n", status)
}
name, ok := doterr.ErrValue[string](err, "parameter_name")
func Errors ¶
Errors returns the errors stored on a doterr entry. If err is a doterr entry, returns its errors. If err is a joined error (has Unwrap() []error), scans immediate children left-to-right and returns errors from the first doterr entry found. Otherwise returns nil. The returned slice preserves insertion order and is a copy.
Note: These errors may be sentinel errors (e.g., ErrRepo), custom error types (e.g., *rfc9457.Error), or any other error type stored in the entry.
func ExtractValueFromBytes ¶
ExtractValueFromBytes extracts a single value from JSON bytes - convenience wrapper
func ExtractValueFromReader ¶
ExtractValueFromReader extracts a single value from JSON - convenience wrapper
func ExtractValuesFromBytes ¶
func ExtractValuesFromBytes(jsonBytes []byte, selectors []Selector) (valuesMap ValuesMap, found []Selector, err error)
ExtractValuesFromBytes is a convenience wrapper for ExtractValuesFromReader
func ExtractValuesFromReader ¶
func ExtractValuesFromReader(reader io.Reader, selectors []Selector) (valuesMap ValuesMap, notFound []Selector, err error)
ExtractValuesFromReader processes multiple selectors in a single pass through JSON. Returns values for found selectors, list of selectors that were found, and any errors. Continues processing all selectors even when some fail to provide comprehensive error reporting.
func FindErr ¶
FindErr walks an error tree (including errors.Join trees) and returns the first match for target (via errors.As).
func NewErr ¶
NewErr builds a standalone structured entry (no primary cause inside). Accepted parts:
- error — sentinel/tag (required: at least one, must be first)
- KV{Key,Value} — explicit key/value
- "key", value — implicit pair (value can be any type, including error)
- error — optional trailing cause (joined last via errors.Join)
Pattern: one or more sentinels (error), then zero or more key-value pairs, then optional trailing cause (error). After the first string key, all remaining args must form valid pairs, except for an optional final error. Returns nil if no meaningful parts are provided after validation. Returns a validation error joined with the partial entry if validation fails.
func WithErr ¶
WithErr is a flexible enrichment helper. Typical uses:
// Enrich an existing composite error (err may be an errors.Join tree):
err = doterr.With(err, "Foo", 10)
// Build an entry and join a trailing cause in one shot:
err = doterr.With("endpoint", ep, ErrTemplate, cause) // 'cause' is last
Behavior:
If the FIRST arg is an error, it is treated as the base error to enrich: • If it is a doterr entry, merge KVs/sentinels into that entry. • If it is a multi-unwrap (errors.Join tree), find the RIGHTMOST doterr entry, merge into it, and rebuild preserving order. • If no doterr entry is found, a new entry will be joined in (see step 3).
After consuming the base (if present), if the LAST remaining arg is an error, it is treated as the CAUSE and joined LAST.
The remaining middle args (if any) are collected into an entry. If we enriched an existing doterr entry in step 1, that merged entry is used; otherwise, a fresh entry is created. If there is a trailing CAUSE from step 2, the result is errors.Join(entry, cause). If there is no cause, the entry is returned.
Note: For inter-function composition, prefer New() with trailing cause:
return doterr.New(ErrRepo, "key", val, cause) // cause last
Types ¶
type KV ¶
KV represents a key/value metadata pair. Keys are preserved in insertion order, and values may be of any type.
func ErrMeta ¶
ErrMeta returns the key/value pairs stored on a doterr entry. If err is a doterr entry, returns its metadata. If err is a joined error (has Unwrap() []error), scans immediate children left-to-right and returns metadata from the first doterr entry found. Otherwise returns nil. The returned slice preserves insertion order and is a copy.