errcontext

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package errcontext attaches structured logging context to errors. It wraps errors with a Context map using xerrors.Extend, enabling downstream callers to extract slog.Attr key-value pairs for logging.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Add

func Add(err error, context ...slog.Attr) error

Add attaches the given slog.Attr key-value pairs to err as logging context. If err already has a Context, the existing map is mutated in place (last-entry-wins). Returns nil if err is nil, or err unchanged if no attrs are provided.

Example
package main

import (
	"errors"
	"log/slog"
	"os"

	"github.com/wood-jp/xerrors"
	"github.com/wood-jp/xerrors/errcontext"
)

func newLogger() *slog.Logger {
	return slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			return a
		},
	}))
}

func main() {
	err := errors.New("request failed")
	err = errcontext.Add(err,
		slog.String("user_id", "u123"),
		slog.Int("status", 503),
	)
	newLogger().Error("handler error", xerrors.Log(err))
}
Output:
{"level":"ERROR","msg":"handler error","error":{"error":"request failed","error_detail":{"context":{"status":503,"user_id":"u123"}}}}

Types

type Context

type Context map[string]slog.Value

Context is a map of key-value pairs attached to an error for structured logging.

func Get

func Get(err error) Context

Get extracts the Context attached to err, or nil if none is present.

func (Context) Flatten

func (c Context) Flatten() []slog.Attr

Flatten returns the context as a slice of slog.Attr sorted by key.

func (Context) LogValue

func (c Context) LogValue() slog.Value

LogValue implements slog.LogValuer. An empty context returns an empty group. A non-empty context returns a group containing a single "context" attr whose value is a group of the key-value pairs in sorted key order.

Jump to

Keyboard shortcuts

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