errors

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

errors-go

pleme-io's standard error model for Go. One concrete error type carries a message, a cause chain, an optional machine code, and a severity — the Go counterpart to the Rust fleet's anyhow + thiserror, with the severity ladder from pleme-actions-shared folded in.

Pure standard library. No dependencies. Drop it into any module and it stays fully interoperable with errors.Is, errors.As, errors.Unwrap, and fmt.Errorf("%w", …).

What

A single importable Go package (Biblioteca) providing one concrete Error type plus a small, orthogonal API around it: New / Wrap for construction, WithSeverity / WithCode options, SeverityOf / CodeOf for chain-walking inspection, and Join for aggregation. It mirrors the pleme-io Rust fleet's anyhow + thiserror ergonomics and folds in the pleme-actions-shared severity ladder, while remaining a drop-in companion to the stdlib errors package.

Why

Three concerns recur in every fleet service, and the stdlib errors package solves only the first:

Concern Rust analog This package
Free-form context wrapping anyhow .context(...) Wrap
Typed, inspectable sentinels + codes thiserror New + WithCode
Operator-facing severity pleme-actions-shared Severity + SeverityOf

Rather than a parallel error hierarchy, everything is one type — Error — that satisfies error and unwraps transparently. You keep using the stdlib errors package for everything else.

Install

go get github.com/pleme-io/errors-go
import errs "github.com/pleme-io/errors-go"

Nix (build-verification check via the substrate go-library-flake):

nix build github:pleme-io/errors-go        # runs `go build ./...` in the sandbox
nix run github:pleme-io/errors-go#check-all # full GSDS check surface

Usage

Wrapping (anyhow)

Wrap adds context while preserving the cause for errors.Is/errors.As. It returns nil when given nil, so it is safe in a tail position:

func reconcile() error {
    if err := loadConfig(); err != nil {
        return errs.Wrap(err, "reconcile tenant config")
    }
    return nil
}

A fully wrapped chain renders outermost-intent first:

serve request: reconcile: load tenant: not found

By default a wrap inherits the wrapped error's severity, so context-only wrapping never silently downgrades a failure. Pass WithSeverity to re-classify.

Typed sentinels (thiserror)

Define sentinels with New; match them across any number of wraps with the stdlib errors.Is:

var ErrNotFound = errs.New("resource not found", errs.WithCode("E_NOT_FOUND"))

err := errs.Wrap(errs.Wrap(ErrNotFound, "fetch from store"), "handle request")

errors.Is(err, ErrNotFound) // true, across both wraps
errs.CodeOf(err)            // "E_NOT_FOUND" — first non-empty code, walking the chain

Recover the typed value with errors.As:

var e *errs.Error
if errors.As(err, &e) {
    _ = e.Severity()
    _ = e.Code()
}
Severity

The ladder mirrors pleme-actions-shared. Constants are prefixed (SeverityNotice/SeverityWarning/SeverityError) — the marquee type is named Error, so a bare Error const would collide with it, exactly the situation log/slog resolves with LevelInfo/LevelWarn.

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)
}

SeverityOf walks the chain and defaults to SeverityError for any error without severity metadata — including plain stdlib errors — so failures are loud by default and a missing annotation is never read as benign.

Aggregation

Join mirrors errors.Join: nil inputs are dropped, the result is nil when all inputs are nil, and errors.Is/errors.As reach every member. On top of that it computes the aggregate's metadata: severity is the most severe member, and the code is the first non-empty member code (argument order).

err := errs.Join(
    errs.New("config A invalid", errs.WithSeverity(errs.SeverityNotice)),
    errs.New("config B invalid", errs.WithSeverity(errs.SeverityWarning), errs.WithCode("E_B")),
)

errs.SeverityOf(err) // SeverityWarning (most severe member)
errs.CodeOf(err)     // "E_B"

The standard library's errors.Join also works on values from this package — use Join when you want the aggregate's severity/code rolled up, and the stdlib's when you don't.

Surface
Symbol Purpose
type Error struct the one concrete error type; Unwrap() error
type Severity int + SeverityNotice / SeverityWarning / SeverityError the ladder; String()
DefaultSeverity SeverityError — the fallback for un-annotated errors
New(msg string, opts ...Option) error leaf / sentinel constructor
Wrap(err error, msg string, opts ...Option) error context wrap; nil in → nil out
WithSeverity(Severity) Option, WithCode(string) Option constructor options
SeverityOf(err error) Severity severity, walking the chain (default SeverityError)
CodeOf(err error) string first non-empty code, walking the chain
Join(errs ...error) error aggregate; rolls up severity (max) and code (first)

Configuration

None. errors-go is a pure-stdlib Biblioteca with no runtime configuration, no environment variables, and no external dependencies — it is configured entirely through its function arguments and the WithSeverity / WithCode options at construction time.

Release

Released via the pleme-io pull-model: a semver git tag (vX.Y.Z) is pushed and proxy.golang.org fetches the module lazily — there is no artifact upload. Each tag corresponds to a dated section in CHANGELOG.md.

Build and test locally:

go build ./...
go test -race -cover ./...   # 100% statement coverage, race-clean
nix flake check              # GSDS build-verification + app surface

Pure stdlib, 100% statement coverage, race-clean.

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

View Source
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

	// ExitUnavailable (EX_UNAVAILABLE) signals a needed service is unavailable —
	// 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.

View Source
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

func AttrsOf(err error) []slog.Attr

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

func CodeOf(err error) string

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

func ExitCodeOf(err error) int

ExitCodeOf reduces err to a deterministic process exit code (§3.5). The reduction, in order:

  1. nil err → ExitOK (0).
  2. An explicit WithExitCode anywhere in the chain (outermost wins) — this is how ErrHelp maps to 0 and usage errors map to ExitUsage.
  3. An external [exitCodeCarrier] (behaviour-over-type, Law 5).
  4. A transient error (IsTemporary) → ExitTempFail (75).
  5. 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

func HintsOf(err error) []string

HintsOf collects every remediation hint in err's cause chain, innermost first. Returns nil when err is nil or carries no hints.

func IsRetryable

func IsRetryable(err error) bool

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

func IsTemporary(err error) bool

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

func Join(errs ...error) error

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

func New(msg string, opts ...Option) error

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

func PublicOf(err error) string

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

func Wrap(err error, msg string, opts ...Option) error

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) Attr

func (b *Builder) Attr(a slog.Attr) *Builder

Attr attaches one structured slog.Attr (compiles to WithAttr).

func (*Builder) Attrs

func (b *Builder) Attrs(attrs ...slog.Attr) *Builder

Attrs attaches several structured attrs (compiles to WithAttrs).

func (*Builder) Code

func (b *Builder) Code(code string) *Builder

Code attaches a machine-readable code (compiles to WithCode).

func (*Builder) ExitCode

func (b *Builder) ExitCode(code int) *Builder

ExitCode maps the error to a process exit code (compiles to WithExitCode).

func (*Builder) Hint

func (b *Builder) Hint(hint string) *Builder

Hint attaches operator-facing remediation guidance (compiles to WithHint).

func (*Builder) New

func (b *Builder) New(msg string) error

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

func (b *Builder) Option(opts ...Option) *Builder

Option appends an arbitrary Option, the escape hatch that keeps the Builder strictly a superset of the option form.

func (*Builder) Public

func (b *Builder) Public(msg string) *Builder

Public sets the safe-to-surface message (compiles to WithPublic).

func (*Builder) Retryable

func (b *Builder) Retryable(retryable bool) *Builder

Retryable opts into the IsRetryable behaviour carrier (compiles to WithRetryable).

func (*Builder) Secret

func (b *Builder) Secret(publicSummary string) *Builder

Secret marks the error as carrying sensitive data, supplying the safe public summary (compiles to MarkSecret).

func (*Builder) Severity

func (b *Builder) Severity(s Severity) *Builder

Severity sets the Severity of the error being built (compiles to WithSeverity).

func (*Builder) Stack

func (b *Builder) Stack() *Builder

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

func (b *Builder) Temporary(temporary bool) *Builder

Temporary opts into the IsTemporary behaviour carrier (compiles to WithTemporary).

func (*Builder) Wrap

func (b *Builder) Wrap(err error, msg string) error

Wrap finalizes the builder into a wrapping Error over err, applying every accumulated option through the package-level Wrap. Like Wrap, it returns nil when err is nil, so it is safe in a tail position.

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

func (e *Error) Attrs() []slog.Attr

Attrs reports this single layer's structured attributes. Prefer the package-level AttrsOf, which accumulates across the whole chain.

func (*Error) Code

func (e *Error) Code() string

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

func (e *Error) Error() string

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

func (e *Error) ExitCode() int

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

func (e *Error) Format(s fmt.State, verb rune)

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

func (e *Error) Hints() []string

Hints reports this single layer's hints. Prefer HintsOf, which accumulates across the whole chain.

func (*Error) LogValue

func (e *Error) LogValue() slog.Value

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

func (e *Error) Public() string

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

func (e *Error) Retryable() bool

Retryable reports whether this layer was marked retryable via WithRetryable. Defaults to false.

func (*Error) Severity

func (e *Error) Severity() 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

func (e *Error) StackPCs() []uintptr

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

func (e *Error) Temporary() bool

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.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the wrapped cause (or nil for a leaf error), letting errors.Is, errors.As, and errors.Unwrap traverse the chain.

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

func StackOf(err error) []Frame

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.

func (Frame) String

func (f Frame) String() string

String renders a frame as "function\n\tfile:line", matching the format the Go runtime uses for panic traces so captured stacks read identically to native ones.

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

func MarkSecret(publicSummary string) Option

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

func WithAttr(a slog.Attr) Option

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

func WithAttrs(attrs ...slog.Attr) Option

WithAttrs attaches several structured pairs at once, the bulk form of WithAttr. Order is preserved and appends to any attrs already set.

func WithCode

func WithCode(code string) Option

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

func WithExitCode(code int) Option

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

func WithHint(hint string) Option

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

func WithPublic(msg string) Option

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

func WithRetryable(retryable bool) Option

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

func WithSeverity(s Severity) Option

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

func WithTemporary(temporary bool) Option

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

func SeverityOf(err error) Severity

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.

func (Severity) String

func (s Severity) String() string

String returns the lowercase name of the severity ("notice", "warning", "error"). Unknown values render as severity(N) so logs stay unambiguous even if the ladder is extended out of band.

Jump to

Keyboard shortcuts

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