Documentation
¶
Overview ¶
Package errors is pleme-io's standard error model for Go services and tools. It is the Go counterpart to the Rust fleet's use of `anyhow` (free-form context wrapping) and `thiserror` (typed, inspectable errors), with the severity ladder from pleme-actions-shared folded in so a single error value carries its message, its cause chain, an optional machine code, and how loudly an operator should hear about it.
The model is deliberately small. Everything is one concrete type — Error — that satisfies the standard library's error interface and participates fully in errors.Is, errors.As, and errors.Unwrap. There is no parallel error hierarchy to learn: you wrap with Wrap, you create with New, you read the metadata back with SeverityOf and CodeOf, and you keep using the stdlib errors package for everything else.
Anyhow analog — context wrapping ¶
if err := step(); err != nil {
return errs.Wrap(err, "reconcile tenant config")
}
Each Wrap adds a layer of human context while preserving the original cause for errors.Is/errors.As. Wrap returns nil when its input is nil, so it is safe to call unconditionally in a tail position.
Thiserror analog — typed sentinels and codes ¶
var ErrNotFound = errs.New("tenant not found", errs.WithCode("E_NOT_FOUND"))
if errors.Is(err, ErrNotFound) { ... } // matches across wraps
code := errs.CodeOf(err) // "E_NOT_FOUND", walks the chain
Severity ladder — pleme-actions-shared ¶
err := errs.New("token nearing expiry", errs.WithSeverity(errs.SeverityWarning))
switch errs.SeverityOf(err) {
case errs.SeverityNotice: // informational
case errs.SeverityWarning: // degraded, still operating
case errs.SeverityError: // failed (the default)
}
Aggregation ¶
Join mirrors errors.Join: it collects several errors into one whose errors.Is/errors.As reach every member. The aggregate's severity is the most severe of its members.
Index ¶
- Constants
- func AttrsOf(err error) []slog.Attr
- func CodeOf(err error) string
- func Exit(err error)
- func ExitCodeOf(err error) int
- func HintsOf(err error) []string
- func IsRetryable(err error) bool
- func IsTemporary(err error) bool
- func Join(errs ...error) error
- func New(msg string, opts ...Option) error
- func PublicOf(err error) string
- func Wrap(err error, msg string, opts ...Option) error
- type Builder
- func (b *Builder) Attr(a slog.Attr) *Builder
- func (b *Builder) Attrs(attrs ...slog.Attr) *Builder
- func (b *Builder) Code(code string) *Builder
- func (b *Builder) ExitCode(code int) *Builder
- func (b *Builder) Hint(hint string) *Builder
- func (b *Builder) New(msg string) error
- func (b *Builder) Option(opts ...Option) *Builder
- func (b *Builder) Public(msg string) *Builder
- func (b *Builder) Retryable(retryable bool) *Builder
- func (b *Builder) Secret(publicSummary string) *Builder
- func (b *Builder) Severity(s Severity) *Builder
- func (b *Builder) Stack() *Builder
- func (b *Builder) Temporary(temporary bool) *Builder
- func (b *Builder) Wrap(err error, msg string) error
- type Error
- func (e *Error) Attrs() []slog.Attr
- func (e *Error) Code() string
- func (e *Error) Error() string
- func (e *Error) ExitCode() int
- func (e *Error) Format(s fmt.State, verb rune)
- func (e *Error) Hints() []string
- func (e *Error) LogValue() slog.Value
- func (e *Error) Public() string
- func (e *Error) Retryable() bool
- func (e *Error) Severity() Severity
- func (e *Error) StackPCs() []uintptr
- func (e *Error) Temporary() bool
- func (e *Error) Unwrap() error
- type Frame
- type Option
- func MarkSecret(publicSummary string) Option
- func WithAttr(a slog.Attr) Option
- func WithAttrs(attrs ...slog.Attr) Option
- func WithCode(code string) Option
- func WithExitCode(code int) Option
- func WithHint(hint string) Option
- func WithPublic(msg string) Option
- func WithRetryable(retryable bool) Option
- func WithSeverity(s Severity) Option
- func WithStack() Option
- func WithTemporary(temporary bool) Option
- type Severity
Constants ¶
const ( // ExitOK is a successful, clean exit. It is also the code ErrHelp maps to: // printing help on request is a success, not a failure. ExitOK = 0 // ExitError is the generic failure code for an error that carries no more // specific mapping — the default [ExitCodeOf] returns for a SeverityError. ExitError = 1 // ExitUsage (EX_USAGE) signals the command was used incorrectly: bad flags, // wrong argument count, malformed syntax. cli-go maps usage errors here. ExitUsage = 64 // ExitDataErr (EX_DATAERR) signals the input data was incorrect. ExitDataErr = 65 // ExitNoInput (EX_NOINPUT) signals an input file did not exist or was // unreadable. ExitNoInput = 66 // ExitNoUser (EX_NOUSER) signals a specified user did not exist. ExitNoUser = 67 // ExitNoHost (EX_NOHOST) signals a specified host did not exist. ExitNoHost = 68 // a catch-all for "a required dependency failed for reasons unrelated to the // invocation". ExitUnavailable = 69 // ExitSoftware (EX_SOFTWARE) signals an internal software error (an invariant // the program itself violated). ExitSoftware = 70 // ExitNoPerm (EX_NOPERM) signals insufficient permission to perform the // operation (distinct from a protocol-level auth failure). ExitNoPerm = 77 // ExitConfig (EX_CONFIG) signals a configuration error. ExitConfig = 78 // ExitTempFail (EX_TEMPFAIL) signals a temporary failure: the operation may // succeed if retried later. It is the natural mapping for an error that // [IsTemporary] classifies as transient. ExitTempFail = 75 )
The exit-code vocabulary is the BSD sysexits.h set, the de-facto convention for well-behaved CLIs (curl, postfix, urfave/cli's ExitCoder all speak it). Re-expressed in-package (Law 6: <300 LOC well-understood constants, no vendoring) so the spelling stays uniform fleet-wide.
const DefaultSeverity = SeverityError
DefaultSeverity is the severity assigned to any Error built without an explicit WithSeverity, and the value SeverityOf returns when no Error in a chain carries severity metadata. Failures are loud by default.
Variables ¶
This section is empty.
Functions ¶
func AttrsOf ¶
AttrsOf collects the structured attributes attached anywhere in err's cause chain, innermost first so the originating context leads and later wraps append. It returns nil when err is nil or carries no attrs. Duplicate keys are preserved (a structured logger renders them all); callers that want last-wins semantics can post-process.
func CodeOf ¶
CodeOf reports the machine-readable code of err by walking its cause chain and returning the first non-empty code it finds, outermost first. It returns "" when err is nil, when nothing in the chain set a code, or when err neither is nor wraps a code-carrying error.
Searching outermost-first means a wrapper may override an inner code by supplying its own via WithCode, while context-only wraps transparently expose the inner error's code.
func Exit ¶
func Exit(err error)
Exit is the single process-exit funnel: it reduces err via ExitCodeOf and terminates the process with that code. It is the *only* owner of os.Exit — no other package (cli-go, borealis, a service main) calls os.Exit directly. A clean run ends:
func main() { errs.Exit(run()) }
Exit does NOT print err; rendering is the caller's job (via borealis), so the funnel stays output-policy-free. A nil err exits 0.
func ExitCodeOf ¶
ExitCodeOf reduces err to a deterministic process exit code (§3.5). The reduction, in order:
- nil err → ExitOK (0).
- An explicit WithExitCode anywhere in the chain (outermost wins) — this is how ErrHelp maps to 0 and usage errors map to ExitUsage.
- An external [exitCodeCarrier] (behaviour-over-type, Law 5).
- A transient error (IsTemporary) → ExitTempFail (75).
- Otherwise the severity default: SeverityNotice/SeverityWarning → ExitOK (a notice/warning is not a process failure), SeverityError → ExitError (1).
The severity default means even a plain stdlib error has a well-defined exit code (1) without any annotation.
func HintsOf ¶
HintsOf collects every remediation hint in err's cause chain, innermost first. Returns nil when err is nil or carries no hints.
func IsRetryable ¶
IsRetryable reports whether err — or anything it wraps — is classified as safe for a retry policy to re-attempt, honouring WithRetryable and any external Retryable() bool contract. Returns false when err is nil or nothing in the chain claims to be retryable.
func IsTemporary ¶
IsTemporary reports whether err — or anything it wraps — is classified as a transient failure. It honours both this package's WithTemporary and any external type satisfying the net.Error-style Temporary() bool contract (Cheney's behaviour-over-type). Returns false when err is nil or nothing in the chain claims to be temporary.
func Join ¶
Join aggregates several errors into one, mirroring errors.Join: nil inputs are dropped, the result is nil when every input is nil, and errors.Is / errors.As reach every joined member.
The returned aggregate is itself inspectable by this package: its severity (via SeverityOf) is the most severe of its members, so joining a SeverityNotice with a SeverityError yields a SeverityError. Its CodeOf is the first non-empty code among its members, in argument order.
func New ¶
New creates a leaf Error with the given message and options. It has no wrapped cause, making it the idiomatic way to define sentinel errors:
var ErrNotFound = errors.New("not found", errors.WithCode("E_NOT_FOUND"))
The returned value's concrete type is *Error; the static return type is the standard error interface so callers compare and wrap it like any other error.
func PublicOf ¶
PublicOf returns the safe-to-surface message for err, searching outermost first so the most context-rich public summary wins (mirroring CodeOf's outermost-wins rule). Returns "" when err is nil or nothing in the chain set a public message — callers should fall back to a generic string, never to err.Error(), when this is empty and the error must be shown to an end user.
func Wrap ¶
Wrap adds a layer of context to err, returning a new Error whose cause is err. It mirrors the anyhow `.context(...)` pattern: the message describes what was being attempted, while the wrapped cause preserves the original error for errors.Is and errors.As.
Wrap returns nil when err is nil, so it is safe to call unconditionally in a tail position:
return errors.Wrap(step(), "reconcile tenant config")
If no WithSeverity option is given, the wrapper inherits err's severity (via SeverityOf) so context-only wrapping never silently downgrades a failure. Pass WithSeverity explicitly to re-classify.
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder is a fluent alternative to the variadic Option form for assembling an Error. It exists for ergonomics only: every method appends the equivalent Option, and Builder.New / Builder.Wrap apply them through the same New / Wrap constructors, so a Builder can express nothing the option form cannot — there is no second construction path or surface to keep in sync (samber/oops ergonomics without divergence).
err := errs.Build().
Code("E_TIMEOUT").
Severity(errs.SeverityWarning).
Hint("increase --timeout").
Attr(slog.Duration("waited", d)).
ExitCode(errs.ExitTempFail).
Temporary(true).
Wrap(cause, "call upstream")
A Builder is a value; copying one copies its accumulated options. The zero Builder is ready to use, though Build reads more clearly at a call site.
func Build ¶
func Build() *Builder
Build returns a fresh, empty Builder. It is the idiomatic entry point to the fluent form.
func (*Builder) ExitCode ¶
ExitCode maps the error to a process exit code (compiles to WithExitCode).
func (*Builder) New ¶
New finalizes the builder into a leaf Error with the given message, applying every accumulated option through the package-level New. It is the fluent equivalent of New(msg, opts...).
func (*Builder) Option ¶
Option appends an arbitrary Option, the escape hatch that keeps the Builder strictly a superset of the option form.
func (*Builder) Public ¶
Public sets the safe-to-surface message (compiles to WithPublic).
func (*Builder) Retryable ¶
Retryable opts into the IsRetryable behaviour carrier (compiles to WithRetryable).
func (*Builder) Secret ¶
Secret marks the error as carrying sensitive data, supplying the safe public summary (compiles to MarkSecret).
func (*Builder) Severity ¶
Severity sets the Severity of the error being built (compiles to WithSeverity).
func (*Builder) Stack ¶
Stack captures the call stack at this point (compiles to WithStack). Note the frames are captured when Builder.New/Builder.Wrap runs the option, not when this method is called, so the stack still originates at the construction site.
func (*Builder) Temporary ¶
Temporary opts into the IsTemporary behaviour carrier (compiles to WithTemporary).
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error is the one concrete error type of this package. It carries a human message, a Severity, an optional machine-readable code, and an optional wrapped cause. It satisfies the standard error interface and exposes Unwrap so errors.Is, errors.As, and errors.Unwrap traverse the cause chain transparently.
Construct an Error with New or Wrap rather than building the struct literal directly; the constructors apply the default severity and keep the invariants (notably the nil-cause short-circuit in Wrap) in one place. The fields are unexported on purpose: read them back through SeverityOf and CodeOf, which walk the whole chain rather than inspecting a single layer.
func (*Error) Attrs ¶
Attrs reports this single layer's structured attributes. Prefer the package-level AttrsOf, which accumulates across the whole chain.
func (*Error) Code ¶
Code reports this single layer's code (which may be ""). Prefer the package-level CodeOf, which walks the chain for the first non-empty code.
func (*Error) Error ¶
Error renders the message, prefixing wrapped causes in the conventional "context: cause" form so a fully wrapped chain reads as a single line from outermost intent to root cause.
func (*Error) ExitCode ¶
ExitCode reports this single layer's explicitly-set exit code. It is only meaningful when WithExitCode was used; ExitCodeOf checks presence via the hasExit flag before trusting it, so an *Error without WithExitCode does not claim exit code 0.
func (*Error) Format ¶
Format implements fmt.Formatter so the "%+v" verb prints the error message followed by the captured call stack (Dave Cheney's convention), while "%v" and "%s" stay the plain single-line message. This keeps provenance invisible in normal use yet one verb away during triage:
log.Printf("%+v", err) // message + stack
fmt.Println(err) // message only
func (*Error) Hints ¶
Hints reports this single layer's hints. Prefer HintsOf, which accumulates across the whole chain.
func (*Error) LogValue ¶
LogValue implements slog.LogValuer so logging an *Error captures its full structured shape, not just its string. A handler invoked with slog.Any("error", err) — or any value group containing one — substitutes this group lazily, only if the record is actually emitted:
logger.Error("reconcile failed", slog.Any("err", err))
yields a "err" group with keys: msg, severity, and (when set) code, exit_code, hints, public, source, plus every accumulated structured attr from WithAttr/WithAttrs inlined. Walking is chain-aware: severity/code/exit/ hints/public/attrs all come from the package-level chain-walkers, so a wrapped error logs its most context-rich classification. Lazy by construction (LogValuer is only called on emit), so attaching it costs nothing on a dropped record.
func (*Error) Public ¶
Public reports this single layer's public message (may be ""). Prefer PublicOf, which walks the chain for the outermost non-empty one.
func (*Error) Retryable ¶
Retryable reports whether this layer was marked retryable via WithRetryable. Defaults to false.
func (*Error) Severity ¶
Severity reports this single layer's severity. Prefer the package-level SeverityOf, which walks the whole chain; this method exists so an *Error can be inspected directly when you already hold one and to satisfy the severityCarrier interface that SeverityOf looks for.
func (*Error) StackPCs ¶
StackPCs returns this layer's captured program counters (nil if WithStack was not used). It satisfies [stackCarrier] so StackOf can find the stack while walking a chain. Prefer the package-level StackOf, which returns the resolved Frame slice and walks the whole chain.
func (*Error) Temporary ¶
Temporary reports whether this layer was marked transient via WithTemporary. It is present only when explicitly set; an *Error built without WithTemporary does NOT satisfy the temporary contract (its method is only consulted through IsTemporary, which checks presence). Defaults to false.
type Frame ¶
type Frame struct {
// Function is the fully-qualified function name (for example
// "github.com/pleme-io/foo.(*T).Method").
Function string
// File is the absolute source path of the call site.
File string
// Line is the 1-based line number within File.
Line int
}
Frame is one resolved entry in a captured call stack: the function name and the file:line where the WithStack capture saw it. It is the symbolized, human-facing form of a single program counter.
Frames are produced lazily by StackOf / Error.Format, not at capture time: WithStack stores only the raw program counters (one cheap runtime.Callers call), and symbolization happens once, on demand, when a stack is actually rendered. The vast majority of errors are never printed with %+v, so the expensive runtime.CallersFrames walk is deferred until it is known to be needed.
func StackOf ¶
StackOf returns the resolved call stack of err, symbolizing on demand. It walks the cause chain and returns the deepest (innermost) captured stack — the one nearest the originating failure — so that wrapping with additional WithStack options never hides the most useful trace. It returns nil when err is nil or when nothing in the chain captured a stack.
type Option ¶
type Option func(*Error)
Option configures an Error during New or Wrap. Options are applied in the order given, so a later option of the same kind overrides an earlier one.
func MarkSecret ¶
MarkSecret records that this error carries sensitive data and supplies the safe public summary to surface in its place. It is the redaction-by-default posture expressed as an option: where WithPublic adds a friendly summary, MarkSecret asserts that the internal message/attrs must not escape and gives the only string that may.
MarkSecret is shorthand for WithPublic with the additional semantic intent of redaction; the public message it sets is the value PublicOf returns.
func WithAttr ¶
WithAttr attaches a single structured key/value pair to the error being built, recorded as a slog.Attr so it bridges to a structured logger verbatim (see Error.LogValue). Prefer this over folding values into the message: an attr is searchable and machine-readable, a stringly-formatted message is neither.
return errs.Wrap(err, "fetch tenant", errs.WithAttr(slog.String("tenant", id)))
func WithAttrs ¶
WithAttrs attaches several structured pairs at once, the bulk form of WithAttr. Order is preserved and appends to any attrs already set.
func WithCode ¶
WithCode attaches a machine-readable code (for example "E_NOT_FOUND") to the error being built. Codes are free-form; CodeOf returns the first non-empty code found when walking a chain.
func WithExitCode ¶
WithExitCode maps this error layer to a process exit code, consumed by ExitCodeOf / Exit. Use the [sysexits.h]-derived constants (see exit.go) rather than bare integers so the vocabulary stays uniform across the fleet. Exit code 0 is a legitimate explicit choice (it is how cli-go/borealis map `ErrHelp` — a clean, requested early exit), which is why presence is tracked independently of the value.
var ErrUsage = errs.New("bad flags", errs.WithExitCode(errs.ExitUsage))
func WithHint ¶
WithHint attaches operator-facing remediation guidance — what a human should DO about the failure, as opposed to what went wrong. Hints are invisible in Error.Error and surface only through HintsOf and the slog bridge, so a hint never pollutes the error message but is always available to a diagnostics renderer.
errs.New("config not found", errs.WithHint("run `tool init` to scaffold one"))
Multiple hints accumulate across a chain; HintsOf returns them all.
func WithPublic ¶
WithPublic sets the safe-to-surface message: the redacted, end-user-facing summary that omits internal detail. The operator-only message and cause chain remain in Error.Error; the public message is read separately via PublicOf. This is the explicit Public-vs-internal split (samber/oops): one Error value drives both the verbose operator log and the terse user reply.
errs.Wrap(dbErr, "query user by email",
errs.WithPublic("something went wrong, please try again"))
The outermost (most context-rich) public message wins in PublicOf.
func WithRetryable ¶
WithRetryable opts this error into the IsRetryable behaviour carrier: retryable == a caller's retry policy is permitted to re-attempt. Distinct from temporary (a transient-condition signal) so a caller can express "do not retry this even though it looks transient" and vice versa.
func WithSeverity ¶
WithSeverity sets the Severity of the error being built. Without it, an error defaults to DefaultSeverity (Error).
func WithStack ¶
func WithStack() Option
WithStack captures the call stack at the point the option runs, recording it on the error being built. Capture is cheap (a single runtime.Callers call storing raw program counters); symbolization is deferred to render time (see Frame). The stack is invisible in Error.Error — it surfaces only through StackOf or the "%+v" verb of Error.Format, so adding provenance never changes a single-line error message.
Capture the stack as close to the failure as possible:
if err := step(); err != nil {
return errs.Wrap(err, "reconcile", errs.WithStack())
}
Only the first stack in a chain matters: StackOf returns the deepest (innermost) captured stack, which is the one nearest the originating call, so re-capturing on every wrap is wasteful but harmless.
func WithTemporary ¶
WithTemporary opts this error into the IsTemporary behaviour carrier (the net.Error / Cheney convention): temporary == the operation may succeed if retried after a transient condition clears. Classify by behaviour, never by sentinel comparison.
type Severity ¶
type Severity int
Severity is the operator-facing weight of an Error, mirroring the severity ladder used by pleme-actions-shared. Higher values are more severe, so severities compose with the builtin comparison operators and with [max].
const ( // SeverityNotice is informational: something worth recording, but not a // failure and not a degradation. The quietest rung of the ladder. SeverityNotice Severity = iota // SeverityWarning marks a degraded-but-operating condition — a soft // failure, a retry that eventually succeeded, a resource nearing a limit. SeverityWarning // SeverityError marks an outright failure. It is the default severity for // any error created or wrapped without an explicit [WithSeverity], so an // un-annotated error is never silently treated as benign. SeverityError )
The severity constants are prefixed (SeverityNotice, SeverityWarning, SeverityError) because the marquee type of this package is Error — a bare const named Error would collide with it. This mirrors log/slog's LevelInfo/LevelWarn convention exactly.
func SeverityOf ¶
SeverityOf reports the severity of err by walking its cause chain and returning the severity of the outermost error that carries one. It returns DefaultSeverity (SeverityError) when err is nil or when nothing in the chain carries a severity, so any error — including a plain stdlib one — has a well-defined severity.
Because Wrap inherits the wrapped error's severity by default, the value returned here is normally the most context-rich classification available: the outermost explicit annotation wins, and absent any, the original error's severity propagates out through every wrap.