errorfamily

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2026 License: MIT Imports: 9 Imported by: 192

README

go-error-family

Go Reference Go Report Card

Structured error protocol for Go — behavioral classification, exit codes, and diagnostic rules.

Share the protocol, not the implementation.


The Problem

Every Go program has if err != nil. But what do you do with that error?

Question Before After
Should the caller retry? if strings.Contains(err.Error(), "timeout") errorfamily.IsRetryable(err)
What exit code? os.Exit(1) for everything errorfamily.ExitCode(err) — context-aware
What message for the user? fmt.Println(err) — often internal jargon Structured What/Why/Fix/WayOut
Is it the user's fault or the system's? Guess from the string errorfamily.Classify(err).Audience()

go-error-family answers all of these with a single concept: Family.

Installation

go get github.com/larsartmann/go-error-family

Requires Go 1.26+ (uses errors.AsType).

This is a Go workspace. The root module provides core types and classification. Diagnostic submodules (diagnose/git, diagnose/postgres) require separate imports.

Quick Start

package main

import (
    "errors"
    "os"

    "github.com/larsartmann/go-error-family"
)

func main() {
    err := errors.New("connection refused")

    family := errorfamily.Classify(err)
    // → Transient (default: unknown errors are retryable)

    if errorfamily.IsRetryable(err) {
        // yes — schedule a retry with backoff
    }

    os.Exit(errorfamily.ExitCode(err))
    // → 75 (EX_TEMPFAIL: temporary failure)
}

For your own errors, attach a Family at creation time:

err := errorfamily.NewRejection("file.not_found", "config file missing").
    WithContext("path", "/etc/app/config.yaml")

os.Exit(errorfamily.HandleError(err))
// stderr: "A required resource was not found."
// stderr: "Check that the path and resource name are correct."
// exit: 1

See examples/ for runnable CLI, HTTP, and custom diagnostic rule demos.

What It Gives You

  • Family — behavioral classification (Rejection, Conflict, Transient, Corruption, Infrastructure) that maps to retry decisions, exit codes, and user-facing tone
  • Small interfaces — Coded, Classified, Contextual, Retryable — each error type implements what it needs
  • Classify(err) — universal classification for any error (multi-error → interface → registered sentinels → default)
  • ExitCode(err) — BSD sysexits.h exit codes derived from Family
  • HandleError(err) — CLI boundary handler with structured messages (What / Why / Fix / WayOut)
  • Compose(errs...) — combine errors via errors.Join for partial-success patterns
  • Diagnostic rules — deterministic checks (PostgreSQL, filesystem, network, git) that auto-discover why an error occurred
  • AI debug agent — root cause analysis and FixStep suggestions from diagnostic context

The Five Families

Family Retryable Exit Code Whose Fault Tone
Rejection no 1 User Instructional
Conflict no 1 User (needs to resolve) Explanatory
Transient yes 75 System Reassuring
Corruption no 65 Data damage Urgent
Infrastructure no 69 System Apologetic

Each family exposes Audience() (User / Ops / All) and Tone() for presentation-layer decisions.

Constructors

// Simple
err := errorfamily.NewRejection("config.invalid", "bad config")

// With cause
err := errorfamily.WrapTransient(dbErr, "db.timeout", "query timed out")

// With context (chainable)
err := errorfamily.NewRejection("file.not_found", "config missing").
    WithContext("path", "/etc/app/config.yaml").
    WithContext("format", "yaml")

// Formatted
err := errorfamily.Newf(errorfamily.Rejection, "file.not_found", "missing: %s", path)

// Multi-error (partial success)
err := errorfamily.Compose(err1, err2, err3)

Family-specific constructors: NewRejection, NewConflict, NewTransient, NewCorruption, NewInfrastructure. Wrap variants: WrapRejection, WrapConflict, WrapTransient, WrapCorruption, WrapInfrastructure.

Classification

// Classify any error → Family
family := errorfamily.Classify(err)

// Retry decision
if errorfamily.IsRetryable(err) {
    retry(err)
}

// Exit code for CLI
os.Exit(errorfamily.ExitCode(err))

// Parse from string (e.g. config, HTTP headers)
family := errorfamily.ParseFamily("transient") // defaults to Transient for unknowns

Classification precedence — first match wins:

  1. Multi-error (errors.Join) → classify each sub-error, first non-Transient wins
  2. Classified interface → ErrorFamily()
  3. Retryable interface → infer Transient (true) or Rejection (false)
  4. Registered sentinels via errors.Is chain walk
  5. Default → Transient (fail-open for retry)

Registering Third-Party Errors

For errors you don't own (stdlib, libraries):

func init() {
    errorfamily.RegisterClassification(sql.ErrConnDone, errorfamily.Transient)
    errorfamily.RegisterClassification(os.ErrPermission, errorfamily.Rejection)

    // Batch registration
    errorfamily.RegisterClassifications(map[error]errorfamily.Family{
        sql.ErrConnDone: errorfamily.Transient,
        sql.ErrTxDone:   errorfamily.Transient,
    })
}

Implementing Your Own Error Type

You don't have to use the built-in Error struct. Implement the interfaces you need:

package mypkg

import (
    "fmt"

    "github.com/larsartmann/go-error-family"
)

type FindingError struct {
    Category string
    Message  string
    File     string
    Line     int
    Cause    error
}

func (e *FindingError) Error() string          { return e.Message }
func (e *FindingError) Unwrap() error          { return e.Cause }
func (e *FindingError) ErrorCode() string      { return e.Category }
func (e *FindingError) ErrorFamily() errorfamily.Family {
    switch e.Category {
    case "validation":
        return errorfamily.Rejection
    case "io":
        return errorfamily.Transient
    default:
        return errorfamily.Infrastructure
    }
}
func (e *FindingError) ErrorContext() map[string]string {
    return map[string]string{"file": e.File, "line": fmt.Sprintf("%d", e.Line)}
}

Now Classify(), IsRetryable(), ExitCode(), and HandleError() all work with your type.

CLI Boundary: HandleError

HandleError is the top-of-main handler that classifies the error, picks an exit code, formats a user-facing message, and writes to stderr:

func main() {
    if err := run(); err != nil {
        os.Exit(errorfamily.HandleError(err))
    }
}

For more control:

// Structured result (no stderr write) — for HTTP handlers, gRPC interceptors
result := errorfamily.HandleErrorDetailed(err)
fmt.Printf("exit=%d msg=%q fix=%q\n", result.ExitCode, result.Message, result.SuggestedFix)

// Template-aware structured result
result := errorfamily.HandleErrorDetailedWithConfig(err, cfg)

// Context-propagating handler — preferred when you have a context.Context
exitCode := errorfamily.HandleErrorWithContext(ctx, err, errorfamily.HandleConfig{
    Diagnose:    true,
    Output:      myWriter,
    DiagnosticFunc: myDiagnoseFunc,
    OnDiagnosed: func(err error, findings []errorfamily.DiagnosticFinding) {
        logFindings(findings)
    },
    TemplateOverride: map[string]errorfamily.MessageTemplate{
        "file.not_found": {
            What:   "Could not find {{.path}}",
            Why:    "The file doesn't exist at the expected location.",
            Fix:    "Check that {{.path}} exists and is readable.",
            WayOut: "Run with --verbose for more details.",
        },
    },
})
Template Resolution

Messages are resolved in this order (first match wins):

  1. HandleConfig.TemplateOverride[code] — per-call consumer override
  2. RegisterTemplate(code, tmpl) — global registry
  3. Built-in defaultMessages[code] — exact-match defaults
  4. Family.DefaultMessage() — generic family-based fallback

All lookups are exact code matches (case-insensitive). No substring matching.

Register templates globally for reusable error codes:

errorfamily.RegisterTemplate("db.timeout", errorfamily.MessageTemplate{
    What: "Database connection timed out.",
    Why:  "The database server did not respond within the deadline.",
    Fix:  "Check database health and network connectivity.",
})

Diagnostic Rules

Auto-discover why an error occurred:

runner := diagnose.DefaultRunner()
results := runner.Run(ctx, err)

for _, r := range results {
    if r.Status == diagnose.StatusFailed {
        fmt.Println(r.Summary)
        fmt.Println("  Fix:", r.SuggestedFix)
    }
}

Built-in rules (zero-dependency, included in DefaultRunner):

  • FilesystemRule — checks path existence, permissions, writability
  • NetworkRule — checks DNS resolution, TCP connectivity

Opt-in submodules (import explicitly):

import (
    "github.com/larsartmann/go-error-family/diagnose/git"
    "github.com/larsartmann/go-error-family/diagnose/postgres"
)

runner := diagnose.NewRunner(&git.GitRule{}, &postgres.PostgresRule{}, &diagnose.FilesystemRule{})
  • GitRule (diagnose/git) — checks repo state, merge conflicts, remote reachability
  • PostgresRule (diagnose/postgres) — checks pg_isready, TCP connectivity

Results include Confidence (0.0–1.0) and are sorted by confidence descending.

Writing Custom Rules

Use RuleSpec for data-driven matching — the simplest and most common pattern:

type RateLimitRule struct{}

const keyRetryAfter diagnose.ContextKey = "retry_after"

var rateLimitSpec = diagnose.RuleSpec{
    ContextKeys:  []diagnose.ContextKey{keyRetryAfter},
    CodeContains: []string{"rate.limit", "too_many_requests"},
}

func (r *RateLimitRule) Name() string              { return "rate_limit" }
func (r *RateLimitRule) Applicable(err error) bool { return rateLimitSpec.Matches(err) }

func (r *RateLimitRule) Run(ctx context.Context, err error) (*diagnose.DiagnosticResult, error) {
    retryAfter := diagnose.ResolveContextKey(err, []string{"retry_after"}, "unknown")
    // ... check system state ...
    return &diagnose.DiagnosticResult{
        Status:       diagnose.StatusDegraded,
        Confidence:   diagnose.ConfidenceHigh,
        Summary:      "Rate limited — retry after " + retryAfter,
        SuggestedFix: "Wait for the duration specified in the Retry-After header",
    }, nil
}

For testable rules that shell out, accept a CommandRunner:

type MyRule struct {
    Runner diagnose.CommandRunner // inject mock in tests; defaults to DefaultCommandRunner{}
}

See the custom rule example for a complete working example.

AI Debug Agent

Root cause analysis and fix suggestions from diagnostic context:

ag := agent.New(agent.Config{Enabled: true})
result, _ := ag.Analyze(ctx, err, diagnosis)

fmt.Println("Root cause:", result.RootCause)
fmt.Println("Confidence:", result.Confidence)
for _, step := range result.FixSteps {
    fmt.Printf("  - %s\n    Command: %s\n", step.Description, step.Command)
}

The agent produces analysis but does not execute fixes — the consumer decides what to do with FixStep.Command.

AgentResult fields: RootCause, Confidence, Explanation, FixSteps.

Performance

Zero-allocation hot paths. Benchmarks on AMD Ryzen 9 7950X:

Operation Time Allocs
Classify (built-in Error) ~9 ns 0
Classify (plain error) ~30 ns 0
IsRetryable ~9 ns 0
ExitCode ~9 ns 0
WithContext ~8 ns 0
ParseFamily ~12 ns 0
HandleError (with context) ~450 ns 5
Runner.Run (1 rule) ~420 ns 5

HandleError includes template resolution and stderr write. Use HandleErrorDetailed when you only need the structured result.

Architecture

go-error-family/
├── family.go               — Family enum + data-driven familyData
├── interfaces.go           — Coded, Classified, Contextual, Retryable (each embeds error)
├── error.go                — Reference Error struct (Is, Unwrap, Format, WithContext, accessors)
├── classify.go             — Classify, IsRetryable, ExitCode, RegisterClassification(s)
├── constructors.go         — New, Wrap, Newf, Wrapf + family-specific shortcuts
├── handle.go               — HandleError, HandleErrorWithContext, template system
├── diagnose/
│   ├── diagnose.go         — Runner, DiagnosticRule, RuleSpec, CommandRunner, ContextKey
│   ├── context.go          — RunCommand, CommandExists (exported for rule authors)
│   ├── rules_filesystem.go — FilesystemRule
│   ├── rules_network.go    — NetworkRule
│   ├── git/                — submodule: GitRule
│   └── postgres/           — submodule: PostgresRule
├── agent/
│   └── agent.go            — DebugAgent interface, Config, AgentResult, FixStep
└── examples/
    ├── cmd/cli             — CLI boundary handler example
    ├── cmd/http            — HTTP middleware with status code mapping
    └── cmd/custom_rule     — Writing your own DiagnosticRule

When to Use / When Not To

Use this when you need behavior derived from errors: retry decisions, exit codes, user-facing messages, or diagnostic investigation — especially at program boundaries (CLI top-level, HTTP handlers, gRPC interceptors).

Don't use this when a simple fmt.Errorf("...: %w", err) is enough. If you only need to wrap and propagate, the standard library is fine. This library shines when errors need to drive behavior.

Philosophy

  1. Protocol, not framework — share the vocabulary, not the implementation
  2. Each error type implements what it needs — no god struct
  3. Presentation is separate from the error — the CLI layer formats for humans
  4. Family = exit code = retry decision = tone — one concept, many audiences
  5. Generic errors are structurally impossible — Code + Family + Context guarantee specificity

License

MIT — Copyright (c) 2026 Lars Artmann

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Compose added in v0.3.0

func Compose(errs ...error) error

Compose combines multiple errors using errors.Join. The result can be passed to Classify to determine the worst Family (first non-Transient wins) or to ExitCode for the appropriate exit code.

Returns nil if no errors are provided or all are nil.

func ExitCode

func ExitCode(err error) int

ExitCode returns the appropriate process exit code for an error. Nil errors return 0. Other errors are classified and mapped to BSD sysexits.h codes.

func HandleError

func HandleError(err error) int

HandleError is the CLI boundary handler — the meta service.

Call this exactly once at the top of main():

func main() {
    if err := run(); err != nil {
        os.Exit(errorfamily.HandleError(err))
    }
}

It:

  1. Classifies the error (Family → exit code)
  2. Extracts Code and Context for specific messaging
  3. Optionally runs diagnostic rules
  4. Formats a Wix-quality message for the user
  5. Writes to stderr and returns the exit code
Example
err := NewRejection("file.not_found", "config missing").
	WithContext("path", "/etc/app/config.yaml")
_ = HandleError(err)

func HandleErrorWithConfig

func HandleErrorWithConfig(err error, cfg HandleConfig) int

HandleErrorWithConfig is the configurable version of HandleError.

func HandleErrorWithContext added in v0.3.0

func HandleErrorWithContext(ctx context.Context, err error, cfg HandleConfig) int

HandleErrorWithContext handles an error with caller-provided context for cancellation and diagnostic propagation. This is the preferred entry point when the caller has a context.Context available.

All other HandleError variants delegate to this function.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable reports whether the error is worth retrying. Uses Classify() and checks if the result is Transient.

func RegisterClassification

func RegisterClassification(sentinel error, family Family)

RegisterClassification maps a third-party sentinel error to a Family. Thread-safe. Call from init() in external packages:

func init() {
    errorfamily.RegisterClassification(sql.ErrConnDone, errorfamily.Transient)
}

This is for errors you don't own (stdlib, libraries). For your own errors, implement the Classified interface instead.

func RegisterClassifications

func RegisterClassifications(classifications map[error]Family)

RegisterClassifications registers multiple sentinel-to-Family mappings at once. Thread-safe. Call from init() in external packages.

func RegisterTemplate

func RegisterTemplate(code string, tmpl MessageTemplate)

RegisterTemplate adds a MessageTemplate for a specific error code. Thread-safe. Overrides any existing template for the same code.

func UnregisterClassification added in v0.3.0

func UnregisterClassification(sentinel error)

UnregisterClassification removes a previously registered sentinel mapping. Thread-safe. No-op if the sentinel has no registered classification.

func UnregisterTemplate added in v0.3.0

func UnregisterTemplate(code string)

UnregisterTemplate removes a previously registered template. Thread-safe. No-op if the code has no registered template.

Types

type Audience

type Audience int

Audience describes who should be notified about this error.

const (
	// AudienceUser indicates the error is the requester's concern.
	AudienceUser Audience = iota
	// AudienceOps indicates the error needs operational intervention.
	AudienceOps
	// AudienceAll indicates all parties should be notified.
	AudienceAll
)

func (Audience) String added in v0.1.2

func (a Audience) String() string

String returns the lowercase name of the Audience (e.g. "user", "ops").

type Classified

type Classified interface {
	error
	ErrorFamily() Family
}

Classified provides behavioral classification. Required for: retry decisions, exit codes, circuit breakers, tone selection.

type Coded

type Coded interface {
	error
	ErrorCode() string
}

Coded provides machine-readable identity. Required for: metric labels, log fields, message templates, exit code mapping.

type Contextual

type Contextual interface {
	error
	ErrorContext() map[string]string
}

Contextual provides factual details about the error. Required for: structured logging, specific error messages, debug context, and triggering diagnostic rules.

type DiagnosticFinding

type DiagnosticFinding struct {
	// RuleName identifies which diagnostic rule produced this finding.
	RuleName string
	// Status is the check outcome: "healthy", "degraded", "failed", or "unknown".
	Status string
	// Summary is a human-readable explanation of the finding.
	Summary string
	// SuggestedFix is an actionable resolution suggested by the rule.
	SuggestedFix string
	// Confidence is 0.0–1.0 indicating how likely this explains the error.
	Confidence float64
}

DiagnosticFinding is a minimal result type for the CLI boundary. Avoids importing diagnose while preserving type safety.

type DiagnosticFunc

type DiagnosticFunc func(ctx context.Context, err error) []DiagnosticFinding

DiagnosticFunc runs diagnostics for an error and returns results. The diagnose.Runner satisfies this via its Run method.

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error is the reference implementation of a classified, structured error.

Projects with simple error needs can use this directly. Projects with domain-specific needs (e.g., FindingError with Position/File) can build their own struct and implement the Coded/Classified/Contextual interfaces.

Implements: error, Coded, Classified, Contextual, Retryable, fmt.Formatter.

func New

func New(family Family, code, message string) *Error

New creates a new Error with the given family, code, and message.

func NewConflict

func NewConflict(code, message string) *Error

NewConflict creates a Conflict error (version mismatch, duplicate).

func NewCorruption

func NewCorruption(code, message string) *Error

NewCorruption creates a Corruption error (data damaged, not self-healable).

func NewInfrastructure

func NewInfrastructure(code, message string) *Error

NewInfrastructure creates an Infrastructure error (system cannot serve).

func NewRejection

func NewRejection(code, message string) *Error

NewRejection creates a Rejection error (bad input, unauthorized, not found).

func NewTransient

func NewTransient(code, message string) *Error

NewTransient creates a Transient error (temporary failure, retryable).

Example
err := NewTransient("db.timeout", "query took too long").
	WithContext("host", "localhost").
	WithContext("port", "5432")
fmt.Println(err)
Output:
[transient:db.timeout] query took too long

func Newf

func Newf(family Family, code, format string, args ...any) *Error

Newf creates a new Error with a formatted message.

func Wrap

func Wrap(err error, family Family, code, message string) *Error

Wrap wraps an existing error with family, code, and message. Returns nil if err is nil.

func WrapConflict

func WrapConflict(err error, code, message string) *Error

WrapConflict wraps an error as Conflict.

func WrapCorruption

func WrapCorruption(err error, code, message string) *Error

WrapCorruption wraps an error as Corruption.

func WrapInfrastructure

func WrapInfrastructure(err error, code, message string) *Error

WrapInfrastructure wraps an error as Infrastructure.

func WrapRejection

func WrapRejection(err error, code, message string) *Error

WrapRejection wraps an error as Rejection.

Example
orig := errors.New("file does not exist")
err := WrapRejection(orig, "config.invalid", "bad configuration")
fmt.Println(err)
Output:
[rejection:config.invalid] bad configuration: file does not exist

func WrapTransient

func WrapTransient(err error, code, message string) *Error

WrapTransient wraps an error as Transient (retryable).

func Wrapf

func Wrapf(err error, family Family, code, format string, args ...any) *Error

Wrapf wraps an error with a formatted message. Returns nil if err is nil.

func (*Error) Cause

func (e *Error) Cause() error

Cause returns the underlying error in the chain.

func (*Error) Code

func (e *Error) Code() string

Code returns the machine-readable error code. Convenience accessor for direct use without interface assertion.

func (*Error) ContextValue

func (e *Error) ContextValue(key string) string

ContextValue returns a specific context value, or empty string if not present.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface. Returns a compact format: [family:code] message

func (*Error) ErrorCode

func (e *Error) ErrorCode() string

ErrorCode returns the machine-readable error code.

func (*Error) ErrorContext

func (e *Error) ErrorContext() map[string]string

ErrorContext returns a copy of the error's factual context.

func (*Error) ErrorFamily

func (e *Error) ErrorFamily() Family

ErrorFamily returns the behavioral classification.

func (*Error) Family

func (e *Error) Family() Family

Family returns the error's behavioral classification. Convenience accessor for direct use without interface assertion.

func (*Error) Format

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

Format implements fmt.Formatter.

%v    → [family:code] message
%+v   → verbose multi-line with context and cause chain
%s    → message only (no classification prefix)

func (*Error) HasContext

func (e *Error) HasContext(key string) bool

HasContext reports whether the error has a specific context key.

func (*Error) Is

func (e *Error) Is(target error) bool

Is supports errors.Is by matching error code and family. Two errors match if they have the same code AND family.

func (*Error) IsRetryable

func (e *Error) IsRetryable() bool

IsRetryable reports whether this error is worth retrying.

func (*Error) Message

func (e *Error) Message() string

Message returns the human-readable technical message.

func (*Error) Summary

func (e *Error) Summary() string

Summary returns a one-line human-readable summary suitable for logs and CLI output. Format: "code: message" without family prefix.

func (*Error) Timestamp

func (e *Error) Timestamp() time.Time

Timestamp returns when this error was created.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause for error chain traversal.

func (*Error) WithCause

func (e *Error) WithCause(cause error) *Error

WithCause sets the underlying cause and returns the error for chaining.

func (*Error) WithContext

func (e *Error) WithContext(key, value string) *Error

WithContext adds a key-value pair to the error's context. Returns the same error for chaining.

func (*Error) WithTimestamp added in v0.3.0

func (e *Error) WithTimestamp(ts time.Time) *Error

WithTimestamp sets the error timestamp and returns the error for chaining. Useful for testing and deterministic construction.

type Family

type Family int

Family classifies an error's behavioral profile for automated handling.

One concept serving three audiences:

  • Retry loops: "Should I try again?" (Transient = yes)
  • Exit codes: "Which exit code for the shell?" (maps to BSD sysexits.h)
  • Presentation: "Whose fault is it?" (determines tone and framing in user messages)
const (
	// Rejection indicates bad input, unauthorized access, or resource not found.
	// No state changed. Not retryable. User's fault. Tone: helpful, instructional.
	Rejection Family = iota

	// Conflict indicates version mismatch, duplicate creation, or state machine violation.
	// No state changed for requester. Not retryable. User needs to resolve. Tone: explanatory.
	Conflict

	// Transient indicates a temporary infrastructure failure.
	// State unknown. Retryable with backoff. System's fault. Tone: reassuring.
	Transient

	// Corruption indicates the source of truth is damaged (unparseable payload, schema break).
	// Not self-healable. Not retryable. Serious. Tone: urgent, escalate to ops.
	Corruption

	// Infrastructure indicates the system cannot serve (closed, nil deps, startup failure).
	// Not retryable. System's fault. Tone: apologetic.
	Infrastructure
)

func Classify

func Classify(err error) Family

Classify returns the Family of any error by checking multiple sources:

  1. Multi-error support (errors.Join) — first non-Transient wins
  2. Classified interface — the error itself declares its family
  3. Retryable interface — infer from retryability if no family
  4. Registered sentinels — known third-party errors mapped in init()
  5. Default — Transient (fail-open for retry)

Returns Rejection for nil errors.

Example
err := NewRejection("file.not_found", "config missing")
family := Classify(err)
fmt.Println(family.IsRetryable(), family.ExitCode())
Output:
false 1

func ParseFamily

func ParseFamily(s string) Family

ParseFamily parses a family string, case-insensitive. Returns Transient for unrecognized values (fail-open for retry).

Example
fmt.Println(ParseFamily("transient"))
fmt.Println(ParseFamily("UNKNOWN"))
Output:
transient
transient

func (Family) Audience

func (f Family) Audience() Audience

Audience returns who should be notified about errors of this family.

func (Family) DefaultFix added in v0.1.2

func (f Family) DefaultFix() string

DefaultFix returns the default fix suggestion for this family.

func (Family) DefaultMessage

func (f Family) DefaultMessage() string

DefaultMessage returns the default human-readable message for this family.

func (Family) DefaultWhy added in v0.1.2

func (f Family) DefaultWhy() string

DefaultWhy returns the default "why" explanation for this family.

func (Family) ExitCode

func (f Family) ExitCode() int

ExitCode returns the BSD sysexits.h compatible exit code for this family.

func (Family) IsRetryable

func (f Family) IsRetryable() bool

IsRetryable reports whether operations that encounter this error should be retried.

func (Family) IsValid

func (f Family) IsValid() bool

IsValid reports whether the Family value is one of the five defined constants.

func (Family) String

func (f Family) String() string

String returns the lowercase name of the Family (e.g. "transient", "rejection").

func (Family) Tone

func (f Family) Tone() Tone

Tone returns the presentation tone hint for this family.

type HandleConfig

type HandleConfig struct {
	// Output is where human-readable messages are written. Defaults to os.Stderr.
	Output io.Writer

	// Diagnose controls whether automatic diagnostic rules are run.
	Diagnose bool

	// TemplateOverride overrides the default message template for a specific error code.
	// map[errorCode]MessageTemplate
	TemplateOverride map[string]MessageTemplate

	// DiagnosticFunc runs diagnostics for the error. If nil, no diagnostics run.
	DiagnosticFunc DiagnosticFunc

	// OnDiagnosed is called after diagnostics complete, before exit.
	// Receives the error and diagnostic findings. Useful for logging/metrics.
	OnDiagnosed func(err error, findings []DiagnosticFinding)
}

HandleConfig controls how HandleError processes an error at the CLI boundary.

type HandleResult

type HandleResult struct {
	// ExitCode is the process exit code derived from the error's Family.
	ExitCode int
	// Message is the human-readable error message.
	Message string
	// SuggestedFix is an actionable suggestion for resolving the error.
	SuggestedFix string
}

HandleResult contains the full output of handling an error at the CLI boundary.

func HandleErrorDetailed

func HandleErrorDetailed(err error) *HandleResult

HandleErrorDetailed returns a structured result without writing output. Useful for HTTP handlers, gRPC interceptors, and programmatic consumers.

Uses the same template resolution chain as HandleError: registered templates, built-in defaults, and family fallbacks.

func HandleErrorDetailedWithConfig added in v0.3.0

func HandleErrorDetailedWithConfig(err error, cfg HandleConfig) *HandleResult

HandleErrorDetailedWithConfig returns a structured result with template overrides.

type MessageTemplate

type MessageTemplate struct {
	// What describes what happened. Supports {{.key}} placeholders from error context.
	What string
	// Why explains why it happened. Supports {{.key}} placeholders.
	Why string
	// Fix suggests how to resolve the error. Supports {{.key}} placeholders.
	Fix string
	// WayOut provides an escape hatch or alternative action. Supports {{.key}} placeholders.
	WayOut string
}

MessageTemplate defines the Wix-style presentation for an error code. Based on the Wix UX framework: What / Why / Fix / WayOut.

type Retryable

type Retryable interface {
	error
	IsRetryable() bool
}

Retryable errors explicitly declare whether they should be retried. Overrides Family-based retry decisions when present.

type Tone

type Tone string

Tone is a presentation tone hint for error messages. Used by the presentation layer to choose appropriate language.

const (
	// ToneInstructional guides the user on how to fix their input.
	ToneInstructional Tone = "instructional"
	// ToneExplanatory explains what happened and why.
	ToneExplanatory Tone = "explanatory"
	// ToneReassuring reassures the user that the issue is temporary.
	ToneReassuring Tone = "reassuring"
	// ToneUrgent signals that immediate action is required.
	ToneUrgent Tone = "urgent"
	// ToneApologetic indicates the system is at fault.
	ToneApologetic Tone = "apologetic"
)

Directories

Path Synopsis
Package agent provides an error analysis agent that uses diagnostic context to produce root cause analysis and fix suggestions.
Package agent provides an error analysis agent that uses diagnostic context to produce root cause analysis and fix suggestions.
bridge module
Package diagnose provides deterministic diagnostic rules that investigate errors by checking the live system state.
Package diagnose provides deterministic diagnostic rules that investigate errors by checking the live system state.
examples module
cmd/cli command
Example: CLI error handler with contextual messages and exit codes.
Example: CLI error handler with contextual messages and exit codes.
cmd/custom_rule command
Example: Writing a custom diagnostic rule.
Example: Writing a custom diagnostic rule.
cmd/http command
Example: HTTP middleware that returns structured error responses with context-aware body JSON and correct HTTP status codes.
Example: HTTP middleware that returns structured error responses with context-aware body JSON and correct HTTP status codes.

Jump to

Keyboard shortcuts

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