Documentation
¶
Overview ¶
Package errorfamily provides structured error classification and handling for Go. Every error gets a behavioral Family (retry/no-retry), a machine-readable code, human-readable context, and optional diagnostics. Designed for CLI and HTTP boundaries.
The contract is the interfaces, not the struct ¶
The public protocol is four small interfaces in interfaces.go: Coded, Classified, Contextual, and Retryable. Each error type implements the combination that makes sense for it; consumers ask for exactly what they need via errors.AsType[T].
The concrete Error type is a reference implementation — convenient for simple needs, but not required. Projects with domain-specific error shapes (a finding with File/Line, an HTTP error with Status) build their own struct and implement only the interfaces they need. Share the protocol, not the implementation.
Stability ¶
The root package (classification core) is the stable foundation. The agent, diagnose, and bridge packages are experimental (v0.x).
Index ¶
- Variables
- 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 RegisterStdlibDefaults(reg *Registry)
- 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) JSON() ([]byte, error)
- 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) WithContextMap(ctx map[string]string) *Error
- func (e *Error) WithContextf(key, format string, args ...any) *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) HTTPStatus() int
- func (f Family) IsRetryable() bool
- func (f Family) IsValid() bool
- func (f Family) MarshalText() ([]byte, error)
- func (f Family) RetryPolicy() RetryPolicy
- func (f Family) Severity() int
- func (f Family) String() string
- func (f Family) Tone() Tone
- func (f *Family) UnmarshalText(text []byte) error
- type HandleConfig
- type HandleResult
- type MessageTemplate
- type Registry
- func (r *Registry) Classify(err error) Family
- func (r *Registry) Clone() *Registry
- func (r *Registry) RegisterClassification(sentinel error, family Family)
- func (r *Registry) RegisterClassifications(classifications map[error]Family)
- func (r *Registry) RegisterTemplate(code string, tmpl MessageTemplate)
- func (r *Registry) RegisterTemplates(templates map[string]MessageTemplate)
- func (r *Registry) UnregisterClassification(sentinel error)
- func (r *Registry) UnregisterTemplate(code string)
- type RetryPolicy
- type Retryable
- type Tone
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultRegistry = NewRegistry()
DefaultRegistry is the package-level Registry used by the convenience functions (Classify, RegisterClassification, RegisterTemplate, etc.) and by HandleError when HandleConfig.Registry is nil.
Functions ¶
func Compose ¶ added in v0.3.0
Compose joins multiple errors into one, preserving all in the Unwrap chain. It is a thin wrapper around errors.Join kept for backward compatibility with consumers that imported Compose before v0.5.0 reorganized the package.
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.
Delegates to DefaultRegistry. For scoped registration, use Registry.RegisterClassification on a custom Registry.
Example ¶
sentinel := errors.New("connection pool exhausted")
RegisterClassification(sentinel, Transient)
family := Classify(sentinel)
fmt.Println(family)
Output: transient
func RegisterClassifications ¶
RegisterClassifications registers multiple sentinel-to-Family mappings at once. Thread-safe. Call from init() in external packages.
func RegisterStdlibDefaults ¶ added in v0.5.0
func RegisterStdlibDefaults(reg *Registry)
RegisterStdlibDefaults registers classification mappings for common Go standard-library errors onto the given Registry. Pass DefaultRegistry to affect the package-level Classify, or a custom Registry for scoped handling.
Ambiguous cases and the rationale for their assigned Family:
- context.DeadlineExceeded → Transient (retryable). Usually means an upstream was slow; a fresh attempt may succeed. If the deadline was set too short by the caller, the fix is at the call site, but the error itself is still transient in nature.
- context.Canceled → Rejection (not retryable). The caller abandoned the operation; retrying without a new request is wrong.
- sql.ErrNoRows / os.ErrNotExist → Rejection. A missing resource is the caller's concern (wrong key / path), not a system fault.
- sql.ErrConnDone → Transient. The connection pool closed a connection; a retry on a fresh connection typically succeeds.
- os.ErrPermission → Rejection. Permission is a caller/environment state, not a transient failure.
This is advisory: applications whose semantics differ should register their own mappings after calling this.
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.
Delegates to DefaultRegistry. For scoped registration, use Registry.RegisterTemplate on a custom Registry.
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.
func ParseAudience ¶ added in v0.4.0
ParseAudience parses an audience string, case-insensitive. Returns AudienceUser for unrecognized values (safest default).
func (Audience) IsValid ¶ added in v0.4.0
IsValid reports whether the Audience value is one of the three defined constants.
func (Audience) MarshalText ¶ added in v0.4.0
MarshalText implements encoding.TextMarshaler for YAML/JSON config.
func (Audience) String ¶ added in v0.1.2
String returns the lowercase name of the Audience (e.g. "user", "ops").
func (*Audience) UnmarshalText ¶ added in v0.4.0
UnmarshalText implements encoding.TextUnmarshaler for YAML/JSON config. Unknown values are parsed as AudienceUser (safest default).
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.
This is a convenience type, not the contract. The public protocol is the Coded/Classified/Contextual/Retryable interfaces — your own domain error types implement only those and need not embed or use this struct.
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) JSON ¶ added in v0.5.0
JSON returns a canonical JSON encoding of the error for API boundaries. The shape is stable: {family, code, message, context, retryable, timestamp}. Use this for HTTP/REST error responses where a structured body is preferable to the [transient:code] message format of Error().
Example ¶
err := NewTransient("db.timeout", "query timed out").
WithContext("host", "db1").
WithTimestamp(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
data, _ := err.JSON()
fmt.Println(string(data))
Output: {"family":"transient","code":"db.timeout","message":"query timed out","context":{"host":"db1"},"retryable":true,"timestamp":"2026-01-01T00:00:00Z"}
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 a new Error, leaving the original unchanged — safe for shared/sentinel errors.
func (*Error) WithContextMap ¶ added in v0.5.0
WithContextMap merges a map of key-value pairs into the error's context. Returns a new Error, leaving the original unchanged. Nil or empty input returns a clone with no added context.
func (*Error) WithContextf ¶ added in v0.5.0
WithContextf adds a formatted key-value pair to the error's context. The value is produced by fmt.Sprintf(format, args...). Returns a new Error, leaving the original unchanged.
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 via RegisterClassification
- Default — Transient (fail-open for retry)
Returns Rejection for nil errors.
This function delegates to DefaultRegistry. For scoped or test-isolated classification, construct a Registry via NewRegistry and use its Classify method.
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) HTTPStatus ¶ added in v0.5.0
HTTPStatus returns the recommended HTTP response status code for this family. Use at HTTP/REST boundaries to translate a classified error into a response code:
Rejection → 400, Conflict → 409, Transient → 503, Corruption → 500, Infrastructure → 503.
Invalid families return 500 (Internal Server Error).
Example ¶
// Translate a family into an HTTP status code at REST boundaries.
err := NewConflict("order.duplicate", "order already exists")
fmt.Println(Classify(err).HTTPStatus())
Output: 409
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.
func (Family) MarshalText ¶ added in v0.4.0
MarshalText implements encoding.TextMarshaler for YAML/JSON config.
Example ¶
f := Transient text, _ := f.MarshalText() fmt.Println(string(text))
Output: transient
func (Family) RetryPolicy ¶ added in v0.5.0
func (f Family) RetryPolicy() RetryPolicy
RetryPolicy returns sensible retry defaults for this family. Only Transient is retryable; all other families return a single-attempt policy.
func (Family) Severity ¶ added in v0.5.0
Severity returns a total order across families for multi-error classification. Higher = worse. Used by Classify to pick the worst sub-error of an errors.Join result deterministically, independent of argument order.
Transient(1) < Rejection(2) < Conflict(3) < Infrastructure(4) < Corruption(5)
This preserves the fail-closed retry guarantee: if ANY sub-error is non-Transient (severity > 1), the joined error is non-Transient.
func (Family) String ¶
String returns the lowercase name of the Family (e.g. "transient", "rejection").
func (*Family) UnmarshalText ¶ added in v0.4.0
UnmarshalText implements encoding.TextUnmarshaler for YAML/JSON config. Unknown values are parsed as Transient (fail-open).
Example ¶
var f Family
_ = f.UnmarshalText([]byte("rejection"))
fmt.Println(f)
Output: rejection
type HandleConfig ¶
type HandleConfig struct {
// Output is where human-readable messages are written. Defaults to os.Stderr.
Output io.Writer
// Registry provides classification sentinels and message templates.
// If nil, DefaultRegistry is used. Set this for test isolation or
// scoped error handling within a single binary.
Registry *Registry
// TemplateOverride overrides the default message template for a specific error code.
// Takes precedence over registered templates.
// map[errorCode]MessageTemplate
TemplateOverride map[string]MessageTemplate
// DiagnosticFunc runs diagnostics for the error. If nil, no diagnostics run.
// When set, diagnostics run automatically — no separate enable flag needed.
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.
Example ¶
err := NewRejection("file.not_found", "config missing").
WithContext("path", "/etc/app/config.yaml")
result := HandleErrorDetailed(err)
fmt.Println("exit:", result.ExitCode)
fmt.Println("fix:", result.SuggestedFix)
Output: exit: 1 fix: Check that the path and resource name are correct.
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 Registry ¶ added in v0.5.0
type Registry struct {
// contains filtered or unexported fields
}
Registry holds classification sentinels and message templates. It is safe for concurrent use. The zero value is not usable — use NewRegistry.
A Registry solves two problems that package-level globals cannot:
- Test isolation: each test can construct its own Registry without polluting global state or needing t.Cleanup(Unregister…) boilerplate.
- Scoped overrides: a service can register sentinels or templates for its own error handling without affecting other parts of the same binary.
The package-level DefaultRegistry is used by the convenience functions (Classify, RegisterClassification, RegisterTemplate, etc.) and by the HandleError family when no custom Registry is provided in HandleConfig.
Sentinels are stored behind an atomic.Pointer to an immutable snapshot: the hot read path (every Classify) is lock-free and allocation-free, while rare writes serialize under the write lock and publish a new snapshot via copy-on-write.
func NewRegistry ¶ added in v0.5.0
func NewRegistry() *Registry
NewRegistry creates an empty Registry ready for use.
Example ¶
// A custom Registry enables test isolation and scoped handling without
// touching the package-level DefaultRegistry.
reg := NewRegistry()
reg.RegisterClassification(errors.New("sentinel"), Transient)
fmt.Println(reg.Classify(errors.New("sentinel")))
Output: transient
func (*Registry) Classify ¶ added in v0.5.0
Classify returns the Family of any error using this registry's sentinel mappings.
Checks in order, first match wins:
- Multi-error (errors.Join) — first non-Transient sub-error wins
- Classified interface — the error itself declares its family
- Retryable interface — infer from retryability
- Registered sentinels in this registry
- Default — Transient (fail-open for retry)
Returns Rejection for nil errors.
func (*Registry) Clone ¶ added in v0.5.0
Clone returns a new Registry with a deep copy of this Registry's sentinels and templates. Mutations to the clone do not affect the original and vice versa. Enables inherit-and-extend patterns: start from DefaultRegistry, clone it, and register scope-specific overrides without touching the global.
func (*Registry) RegisterClassification ¶ added in v0.5.0
RegisterClassification maps a third-party sentinel error to a Family. Thread-safe. Call from init() in external packages:
func init() {
errorfamily.DefaultRegistry.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 (*Registry) RegisterClassifications ¶ added in v0.5.0
RegisterClassifications registers multiple sentinel-to-Family mappings at once. Thread-safe.
func (*Registry) RegisterTemplate ¶ added in v0.5.0
func (r *Registry) 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 (*Registry) RegisterTemplates ¶ added in v0.5.0
func (r *Registry) RegisterTemplates(templates map[string]MessageTemplate)
RegisterTemplates registers multiple code-to-template mappings at once. Thread-safe. Keys are lower-cased for case-insensitive lookup. Parity with Registry.RegisterClassifications for the sentinel side.
func (*Registry) UnregisterClassification ¶ added in v0.5.0
UnregisterClassification removes a previously registered sentinel mapping. Thread-safe. No-op if the sentinel has no registered classification.
func (*Registry) UnregisterTemplate ¶ added in v0.5.0
UnregisterTemplate removes a previously registered template. Thread-safe. No-op if the code has no registered template.
type RetryPolicy ¶ added in v0.5.0
RetryPolicy holds retry parameters derived from a Family. It is advisory: the library does not implement the retry loop — consumers (or retry libraries like failsafe-go) use these as sensible starting defaults.
MaxAttempts is the total number of attempts including the first. Non-retryable families return MaxAttempts=1 (execute once, never retry).
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 |
|---|---|
|
agent
module
|
|
|
bridge
module
|
|
|
diagnose
module
|
|
|
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. |