Documentation
¶
Index ¶
- func Compose(errs ...error) error
- func ExitCode(err error) int
- func HandleError(err error) int
- func HandleErrorWithConfig(err error, cfg HandleConfig) int
- func HandleErrorWithContext(ctx context.Context, err error, cfg HandleConfig) int
- func IsRetryable(err error) bool
- func RegisterClassification(sentinel error, family Family)
- func RegisterClassifications(classifications map[error]Family)
- func RegisterTemplate(code string, tmpl MessageTemplate)
- func UnregisterClassification(sentinel error)
- func UnregisterTemplate(code string)
- type Audience
- type Classified
- type Coded
- type Contextual
- type DiagnosticFinding
- type DiagnosticFunc
- type Error
- func New(family Family, code, message string) *Error
- func NewConflict(code, message string) *Error
- func NewCorruption(code, message string) *Error
- func NewInfrastructure(code, message string) *Error
- func NewRejection(code, message string) *Error
- func NewTransient(code, message string) *Error
- func Newf(family Family, code, format string, args ...any) *Error
- func Wrap(err error, family Family, code, message string) *Error
- func WrapConflict(err error, code, message string) *Error
- func WrapCorruption(err error, code, message string) *Error
- func WrapInfrastructure(err error, code, message string) *Error
- func WrapRejection(err error, code, message string) *Error
- func WrapTransient(err error, code, message string) *Error
- func Wrapf(err error, family Family, code, format string, args ...any) *Error
- func (e *Error) Cause() error
- func (e *Error) Code() string
- func (e *Error) ContextValue(key string) string
- func (e *Error) Error() string
- func (e *Error) ErrorCode() string
- func (e *Error) ErrorContext() map[string]string
- func (e *Error) ErrorFamily() Family
- func (e *Error) Family() Family
- func (e *Error) Format(f fmt.State, verb rune)
- func (e *Error) HasContext(key string) bool
- func (e *Error) Is(target error) bool
- func (e *Error) IsRetryable() bool
- func (e *Error) Message() string
- func (e *Error) Summary() string
- func (e *Error) Timestamp() time.Time
- func (e *Error) Unwrap() error
- func (e *Error) WithCause(cause error) *Error
- func (e *Error) WithContext(key, value string) *Error
- func (e *Error) WithTimestamp(ts time.Time) *Error
- type Family
- func (f Family) Audience() Audience
- func (f Family) DefaultFix() string
- func (f Family) DefaultMessage() string
- func (f Family) DefaultWhy() string
- func (f Family) ExitCode() int
- func (f Family) IsRetryable() bool
- func (f Family) IsValid() bool
- func (f Family) String() string
- func (f Family) Tone() Tone
- type HandleConfig
- type HandleResult
- type MessageTemplate
- type Retryable
- type Tone
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Compose ¶ added in v0.3.0
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 ¶
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 ¶
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:
- Classifies the error (Family → exit code)
- Extracts Code and Context for specific messaging
- Optionally runs diagnostic rules
- Formats a Wix-quality message for the user
- 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 ¶
IsRetryable reports whether the error is worth retrying. Uses Classify() and checks if the result is Transient.
func RegisterClassification ¶
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 ¶
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 Classified ¶
Classified provides behavioral classification. Required for: retry decisions, exit codes, circuit breakers, tone selection.
type Coded ¶
Coded provides machine-readable identity. Required for: metric labels, log fields, message templates, exit code mapping.
type Contextual ¶
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 NewConflict ¶
NewConflict creates a Conflict error (version mismatch, duplicate).
func NewCorruption ¶
NewCorruption creates a Corruption error (data damaged, not self-healable).
func NewInfrastructure ¶
NewInfrastructure creates an Infrastructure error (system cannot serve).
func NewRejection ¶
NewRejection creates a Rejection error (bad input, unauthorized, not found).
func NewTransient ¶
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 WrapConflict ¶
WrapConflict wraps an error as Conflict.
func WrapCorruption ¶
WrapCorruption wraps an error as Corruption.
func WrapInfrastructure ¶
WrapInfrastructure wraps an error as Infrastructure.
func WrapRejection ¶
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 ¶
WrapTransient wraps an error as Transient (retryable).
func (*Error) Code ¶
Code returns the machine-readable error code. Convenience accessor for direct use without interface assertion.
func (*Error) ContextValue ¶
ContextValue returns a specific context value, or empty string if not present.
func (*Error) Error ¶
Error implements the error interface. Returns a compact format: [family:code] message
func (*Error) ErrorContext ¶
ErrorContext returns a copy of the error's factual context.
func (*Error) ErrorFamily ¶
ErrorFamily returns the behavioral classification.
func (*Error) Family ¶
Family returns the error's behavioral classification. Convenience accessor for direct use without interface assertion.
func (*Error) Format ¶
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 ¶
HasContext reports whether the error has a specific context key.
func (*Error) Is ¶
Is supports errors.Is by matching error code and family. Two errors match if they have the same code AND family.
func (*Error) IsRetryable ¶
IsRetryable reports whether this error is worth retrying.
func (*Error) Summary ¶
Summary returns a one-line human-readable summary suitable for logs and CLI output. Format: "code: message" without family prefix.
func (*Error) WithContext ¶
WithContext adds a key-value pair to the error's context. Returns the same error for chaining.
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 ¶
Classify returns the Family of any error by checking multiple sources:
- Multi-error support (errors.Join) — first non-Transient wins
- Classified interface — the error itself declares its family
- Retryable interface — infer from retryability if no family
- Registered sentinels — known third-party errors mapped in init()
- 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 ¶
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) DefaultFix ¶ added in v0.1.2
DefaultFix returns the default fix suggestion for this family.
func (Family) DefaultMessage ¶
DefaultMessage returns the default human-readable message for this family.
func (Family) DefaultWhy ¶ added in v0.1.2
DefaultWhy returns the default "why" explanation for this family.
func (Family) IsRetryable ¶
IsRetryable reports whether operations that encounter this error should be retried.
func (Family) IsValid ¶
IsValid reports whether the Family value is one of the five defined constants.
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 ¶
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" )
Source Files
¶
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. |