ewrap

package module
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2025 License: MIT Imports: 14 Imported by: 15

README

ewrap

Go Docs Go Report Card Go Reference GitHub Sponsors

A sophisticated, modern error handling library for Go applications that provides comprehensive error management with advanced features, observability hooks, and seamless integration with Go 1.25+ features.

Core Features

Error Management & Context
  • Advanced Stack Traces: Programmatic stack frame inspection with iterators and structured access
  • Smart Error Wrapping: Maintains error chains with unified context handling and metadata preservation
  • Rich Metadata: Type-safe metadata attachment with optional generics support
  • Context Integration: Unified context handling preventing divergence between error context and metadata
Logging & Observability
  • Modern Logging: Support for slog (Go 1.21+), logrus, zap, zerolog with structured output
  • Observability Hooks: Built-in metrics and tracing for error frequencies and circuit-breaker states
  • Recovery Guidance: Integrated recovery suggestions in error output and logging
Performance & Efficiency
  • Go 1.25+ Optimizations: Uses maps.Clone and slices.Clone for efficient copying operations
  • Pool-based Error Groups: Memory-efficient error aggregation with errors.Join compatibility
  • Thread-Safe Operations: Zero-allocation hot paths with minimal contention
  • Structured Serialization: JSON/YAML export with full error group serialization
Advanced Features
  • Circuit Breaker Pattern: Protect systems from cascading failures with state transition monitoring
  • Custom Retry Logic: Configurable per-error retry strategies with RetryInfo extension
  • Error Categorization: Built-in types, severity levels, and optional generic type constraints
  • Timestamp Formatting: Proper timestamp formatting with customizable formats

Installation

go get github.com/hyp3rd/ewrap

Documentation

ewrap provides comprehensive documentation covering all features and advanced usage patterns. Visit the complete documentation for detailed guides, examples, and API reference.

Usage Examples

Basic Error Handling

Create and wrap errors with context:

// Create a new error
err := ewrap.New("database connection failed")

// Wrap an existing error with context
if err != nil {
    return ewrap.Wrap(err, "failed to process request")
}

err = ewrap.Newf("failed to process request id: %v", requestID)
Advanced Error Context with Unified Handling

Add rich context and metadata with the new unified context system:

err := ewrap.New("operation failed",
    ewrap.WithContext(ctx, ewrap.ErrorTypeDatabase, ewrap.SeverityCritical),
    ewrap.WithLogger(logger),
    ewrap.WithRecoverySuggestion("Check database connection and retry")).
    WithMetadata("query", "SELECT * FROM users").
    WithMetadata("retry_count", 3).
    WithMetadata("connection_pool_size", 10)

// Log the error with all context and recovery suggestions
err.Log()
Modern Error Groups with errors.Join Integration

Use error groups efficiently with Go 1.25+ features:

// Create an error group pool with initial capacity
pool := ewrap.NewErrorGroupPool(4)

// Get an error group from the pool
eg := pool.Get()
defer eg.Release()  // Return to pool when done

// Add errors as needed
eg.Add(err1)
eg.Add(err2)

// Use errors.Join compatibility for standard library integration
if err := eg.Join(); err != nil {
    return err
}

// Or serialize the entire error group
jsonOutput, _ := eg.ToJSON(ewrap.WithTimestampFormat(time.RFC3339))
Stack Frame Inspection and Iteration

Programmatically inspect stack traces:

if wrappedErr, ok := err.(*ewrap.Error); ok {
    // Get a stack iterator for programmatic access
    iterator := wrappedErr.GetStackIterator()

    for iterator.HasNext() {
        frame := iterator.Next()
        fmt.Printf("Function: %s\n", frame.Function)
        fmt.Printf("File: %s:%d\n", frame.File, frame.Line)
        fmt.Printf("PC: %x\n", frame.PC)
    }

    // Or get all frames at once
    frames := wrappedErr.GetStackFrames()
    for _, frame := range frames {
        // Process each frame...
    }
}
Custom Retry Logic with Extended RetryInfo

Configure per-error retry strategies:

// Define custom retry logic
shouldRetry := func(err error, attempt int) bool {
    if attempt >= 5 {
        return false
    }

    // Custom logic based on error type
    if wrappedErr, ok := err.(*ewrap.Error); ok {
        return wrappedErr.ErrorType() == ewrap.ErrorTypeNetwork
    }
    return false
}

// Create error with custom retry configuration
err := ewrap.New("network timeout",
    ewrap.WithRetryInfo(3, time.Second*2, shouldRetry))

// Use the retry information
if retryInfo := err.GetRetryInfo(); retryInfo != nil {
    if retryInfo.ShouldRetry(err, currentAttempt) {
        // Perform retry logic
    }
}
Observability Hooks and Monitoring

Monitor error patterns and circuit breaker states:

// Set up observability hooks
observer := &MyObserver{
    metricsClient: metricsClient,
    tracer:       tracer,
}

// Create circuit breaker with observability
cb := ewrap.NewCircuitBreaker("payment-service", 5, time.Minute*2,
    ewrap.WithObserver(observer))

// The observer will receive notifications for:
// - Error frequency changes
// - Circuit breaker state transitions
// - Recovery suggestions triggered
Circuit Breaker Pattern

Protect your system from cascading failures:

// Create a circuit breaker for database operations
cb := ewrap.NewCircuitBreaker("database", 3, time.Minute)

if cb.CanExecute() {
    if err := performDatabaseOperation(); err != nil {
        cb.RecordFailure()
        return ewrap.Wrap(err, "database operation failed",
            ewrap.WithContext(ctx, ewrap.ErrorTypeDatabase, ewrap.SeverityCritical))
    }
    cb.RecordSuccess()
}
Complete Example

Here's a comprehensive example combining multiple features:

func processOrder(ctx context.Context, orderID string) error {
    // Get an error group from the pool
    pool := ewrap.NewErrorGroupPool(4)
    eg := pool.Get()
    defer eg.Release()

    // Create a circuit breaker for database operations
    cb := ewrap.NewCircuitBreaker("database", 3, time.Minute)

    // Validate order
    if err := validateOrderID(orderID); err != nil {
        eg.Add(ewrap.Wrap(err, "invalid order ID",
            ewrap.WithContext(ctx, ewrap.ErrorTypeValidation, ewrap.SeverityError)))
    }

    if !eg.HasErrors() && cb.CanExecute() {
        if err := saveToDatabase(orderID); err != nil {
            cb.RecordFailure()
            return ewrap.Wrap(err, "database operation failed",
                ewrap.WithContext(ctx, ewrap.ErrorTypeDatabase, ewrap.SeverityCritical))
        }
        cb.RecordSuccess()
    }

    return eg.Error()
}

Error Types and Severity

The package provides pre-defined error types and severity levels:

// Error Types
ErrorTypeValidation    // Input validation failures
ErrorTypeNotFound      // Resource not found
ErrorTypePermission    // Authorization/authentication failures
ErrorTypeDatabase      // Database operation failures
ErrorTypeNetwork       // Network-related failures
ErrorTypeConfiguration // Configuration issues
ErrorTypeInternal      // Internal system errors
ErrorTypeExternal      // External service errors

// Severity Levels
SeverityInfo      // Informational messages
SeverityWarning   // Warning conditions
SeverityError     // Error conditions
SeverityCritical  // Critical failures

Logging Integration

Implement the Logger interface to integrate with your logging system:

type Logger interface {
    Error(msg string, keysAndValues ...any)
    Debug(msg string, keysAndValues ...any)
    Info(msg string, keysAndValues ...any)
}

Built-in adapters are provided for popular logging frameworks including modern slog support:

// Slog logger (Go 1.21+) - Recommended for new projects
slogLogger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelDebug,
}))
err := ewrap.New("error occurred",
    ewrap.WithLogger(adapters.NewSlogAdapter(slogLogger)))

// Zap logger
zapLogger, _ := zap.NewProduction()
err := ewrap.New("error occurred",
    ewrap.WithLogger(adapters.NewZapAdapter(zapLogger)))

// Logrus logger
logrusLogger := logrus.New()
err := ewrap.New("error occurred",
    ewrap.WithLogger(adapters.NewLogrusAdapter(logrusLogger)))

// Zerolog logger
zerologLogger := zerolog.New(os.Stdout)
err := ewrap.New("error occurred",
    ewrap.WithLogger(adapters.NewZerologAdapter(zerologLogger)))
Recovery Suggestions in Logging

Recovery suggestions are now automatically included in log output:

err := ewrap.New("database connection failed",
    ewrap.WithRecoverySuggestion("Check database connectivity and connection pool settings"))

// When logged, includes recovery guidance for operations teams
err.Log() // Outputs recovery suggestion in structured format

Error Formatting

Convert errors to structured formats with proper timestamp formatting:

// Convert to JSON with proper timestamp formatting
jsonStr, _ := err.ToJSON(
    ewrap.WithTimestampFormat(time.RFC3339),
    ewrap.WithStackTrace(true),
    ewrap.WithRecoverySuggestion(true))

// Convert to YAML with custom formatting
yamlStr, _ := err.ToYAML(
    ewrap.WithTimestampFormat("2006-01-02T15:04:05Z07:00"),
    ewrap.WithStackTrace(true))

// Serialize entire error groups
pool := ewrap.NewErrorGroupPool(4)
eg := pool.Get()
eg.Add(err1)
eg.Add(err2)

// Export all errors in the group
groupJSON, _ := eg.ToJSON(ewrap.WithTimestampFormat(time.RFC3339))
Modern Go Features Integration

Leverage Go 1.25+ features for efficient operations:

// Efficient metadata copying using maps.Clone
originalErr := ewrap.New("base error").WithMetadata("key1", "value1")
clonedErr := originalErr.Clone() // Uses maps.Clone internally

// Error group integration with errors.Join
eg := pool.Get()
eg.Add(err1, err2, err3)
standardErr := eg.Join() // Returns standard errors.Join result

// Use with standard library error handling
if errors.Is(standardErr, expectedErr) {
    // Handle specific error type
}

Performance Considerations

The package is designed with performance in mind and leverages modern Go features:

Go 1.25+ Optimizations
  • Uses maps.Clone and slices.Clone for efficient copying operations
  • Zero-allocation paths for error creation and wrapping in hot paths
  • Optimized stack trace capture with intelligent filtering
Memory Management
  • Error groups use sync.Pool for efficient memory reuse
  • Stack frame iterators provide lazy evaluation
  • Minimal allocations during error metadata operations
Concurrency & Safety
  • Thread-safe operations with low lock contention
  • Atomic operations for circuit breaker state management
  • Lock-free observability hook notifications
Structured Operations
  • Pre-allocated buffers for JSON/YAML serialization
  • Efficient stack trace capture and filtering
  • Optimized metadata storage and retrieval

Observability Features

Built-in Monitoring
  • Error frequency tracking and reporting
  • Circuit breaker state transition monitoring
  • Recovery suggestion effectiveness metrics
Integration Points
// Implement the Observer interface for custom monitoring
type Observer interface {
    OnErrorCreated(err *Error, context ErrorContext)
    OnCircuitBreakerStateChange(name string, from, to CircuitState)
    OnRecoverySuggestionTriggered(suggestion string, context ErrorContext)
}

// Register observers for monitoring
ewrap.RegisterGlobalObserver(myObserver)

Development Setup

  1. Clone this repository:

    git clone https://github.com/hyp3rd/ewrap.git
    
  2. Install VS Code Extensions Recommended (optional):

    {
      "recommendations": [
        "github.vscode-github-actions",
        "golang.go",
        "ms-vscode.makefile-tools",
        "esbenp.prettier-vscode",
        "pbkit.vscode-pbkit",
        "trunk.io",
        "streetsidesoftware.code-spell-checker",
        "ms-azuretools.vscode-docker",
        "eamodio.gitlens"
      ]
    }
    
    1. Install Golang.

    2. Install GitVersion.

    3. Install Make, follow the procedure for your OS.

    4. Set up the toolchain:

      make prepare-toolchain
      
    5. Initialize pre-commit (strongly recommended to create a virtual env, using for instance PyEnv) and its hooks:

       pip install pre-commit
       pre-commit install
       pre-commit install-hooks
    

Project Structure

├── internal/ # Private code
│   └── logger/ # Application specific code
├── pkg/ # Public libraries)
├── scripts/ # Scripts for development
├── test/ # Additional test files
└── docs/ # Documentation

Best Practices

  • Follow the Go Code Review Comments
  • Run golangci-lint before committing code
  • Ensure the pre-commit hooks pass
  • Write tests for new functionality
  • Keep packages small and focused
  • Use meaningful package names
  • Document exported functions and types

Available Make Commands

  • make test: Run tests.
  • make benchmark: Run benchmark tests.
  • make update-deps: Update all dependencies in the project.
  • make prepare-toolchain: Install all tools required to build the project.
  • make lint: Run the staticcheck and golangci-lint static analysis tools on all packages in the project.
  • make run: Build and run the application in Docker.

License

MIT License

Contributing

  1. Fork the repository
  2. Create your feature branch
  3. Commit your changes
  4. Push to the branch
  5. Create a Pull Request

Refer to CONTRIBUTING for more information.

Author

I'm a surfer, and a software architect with 15 years of experience designing highly available distributed production systems and developing cloud-native apps in public and private clouds. Feel free to connect with me on LinkedIn.

LinkedIn

Documentation

Overview

Package ewrap provides enhanced error handling capabilities with stack traces, error wrapping, custom error types, and logging integration.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CaptureStack

func CaptureStack() []uintptr

CaptureStack captures the current stack trace.

func GetMetadataValue added in v1.3.0

func GetMetadataValue[T any](e *Error, key string) (T, bool)

GetMetadataValue retrieves metadata and attempts to cast it to type T.

Types

type CircuitBreaker

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

CircuitBreaker implements the circuit breaker pattern for error handling.

func NewCircuitBreaker

func NewCircuitBreaker(name string, maxFailures int, timeout time.Duration) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker.

func NewCircuitBreakerWithObserver added in v1.3.2

func NewCircuitBreakerWithObserver(name string, maxFailures int, timeout time.Duration, observer Observer) *CircuitBreaker

NewCircuitBreakerWithObserver creates a new circuit breaker with an observer.

func (*CircuitBreaker) CanExecute

func (cb *CircuitBreaker) CanExecute() bool

CanExecute checks if the operation can be executed.

func (*CircuitBreaker) OnStateChange

func (cb *CircuitBreaker) OnStateChange(callback func(name string, from, to CircuitState))

OnStateChange sets a callback for state changes.

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure records a failure and potentially opens the circuit.

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess records a success and potentially closes the circuit.

func (*CircuitBreaker) SetObserver added in v1.3.2

func (cb *CircuitBreaker) SetObserver(observer Observer)

SetObserver sets an observer for the circuit breaker.

type CircuitState

type CircuitState int

CircuitState represents the state of a circuit breaker.

const (
	// CircuitClosed indicates normal operation.
	CircuitClosed CircuitState = iota
	// CircuitOpen indicates the circuit is broken.
	CircuitOpen
	// CircuitHalfOpen indicates the circuit is testing recovery.
	CircuitHalfOpen
)

type Error

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

Error represents a custom error type with stack trace and metadata.

func New

func New(msg string, opts ...Option) *Error

New creates a new Error with a stack trace and applies the provided options.

func Newf

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

Newf creates a new Error with a formatted message and applies the provided options.

func Wrap

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

Wrap wraps an existing error with additional context and stack trace.

func Wrapf

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

Wrapf wraps an error with a formatted message.

func (*Error) CanRetry

func (e *Error) CanRetry() bool

CanRetry checks if the error can be retried.

func (*Error) Cause

func (e *Error) Cause() error

Cause returns the underlying cause of the error.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) GetErrorContext added in v1.3.0

func (e *Error) GetErrorContext() *ErrorContext

GetErrorContext retrieves the context from the error.

func (*Error) GetMetadata

func (e *Error) GetMetadata(key string) (any, bool)

GetMetadata retrieves metadata from the error.

func (*Error) GetStackFrames added in v1.3.2

func (e *Error) GetStackFrames() []StackFrame

GetStackFrames returns all stack frames as a slice.

func (*Error) GetStackIterator added in v1.3.2

func (e *Error) GetStackIterator() *StackIterator

GetStackIterator returns a stack iterator for the error's stack trace.

func (*Error) IncrementRetry

func (e *Error) IncrementRetry()

IncrementRetry increments the retry counter.

func (*Error) Is

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

Is reports whether target matches err in the error chain.

func (*Error) Log

func (e *Error) Log()

Log logs the error using the configured logger.

func (*Error) Stack

func (e *Error) Stack() string

Stack returns the stack trace as a string.

func (*Error) ToJSON

func (e *Error) ToJSON(opts ...FormatOption) (string, error)

ToJSON converts the error to a JSON string.

func (*Error) ToYAML

func (e *Error) ToYAML(opts ...FormatOption) (string, error)

ToYAML converts the error to a YAML string.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap provides compatibility with Go 1.13 error chains.

func (*Error) WithContext added in v1.3.0

func (e *Error) WithContext(ctx *ErrorContext) *Error

WithContext adds context information to the error.

func (*Error) WithMetadata

func (e *Error) WithMetadata(key string, value any) *Error

WithMetadata adds metadata to the error.

type ErrorContext

type ErrorContext struct {
	// Timestamp when the error occurred.
	Timestamp time.Time
	// Type categorizes the error.
	Type ErrorType
	// Severity indicates the error's impact level.
	Severity Severity
	// Operation that was being performed.
	Operation string
	// Component where the error originated.
	Component string
	// RequestID for tracing.
	RequestID string
	// User associated with the operation.
	User string
	// Environment where the error occurred.
	Environment string
	// Version of the application.
	Version string
	// File and line where the error occurred.
	File string
	Line int
	// Additional context-specific data.
	Data map[string]any
}

ErrorContext holds comprehensive information about an error's context.

func (*ErrorContext) String

func (ec *ErrorContext) String() string

String returns a formatted string representation of the error context.

type ErrorGroup

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

ErrorGroup represents a collection of related errors. It maintains a reference to its pool for proper release handling.

func NewErrorGroup

func NewErrorGroup() *ErrorGroup

NewErrorGroup creates a standalone ErrorGroup without pooling. This is useful for cases where pooling isn't needed or for testing.

func (*ErrorGroup) Add

func (eg *ErrorGroup) Add(err error)

Add appends an error to the group if it's not nil.

func (*ErrorGroup) Clear

func (eg *ErrorGroup) Clear()

Clear removes all errors from the group while preserving capacity.

func (*ErrorGroup) Error

func (eg *ErrorGroup) Error() string

Error implements the error interface.

func (*ErrorGroup) ErrorOrNil

func (eg *ErrorGroup) ErrorOrNil() error

ErrorOrNil returns the ErrorGroup itself if it contains errors, or nil if empty.

func (*ErrorGroup) Errors

func (eg *ErrorGroup) Errors() []error

Errors returns a copy of all errors in the group.

func (*ErrorGroup) HasErrors

func (eg *ErrorGroup) HasErrors() bool

HasErrors returns true if the group contains any errors.

func (*ErrorGroup) Join added in v1.3.0

func (eg *ErrorGroup) Join() error

Join aggregates all errors in the group using errors.Join. It returns nil if the group is empty.

func (*ErrorGroup) MarshalJSON added in v1.3.2

func (eg *ErrorGroup) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*ErrorGroup) MarshalYAML added in v1.3.2

func (eg *ErrorGroup) MarshalYAML() (any, error)

MarshalYAML implements the yaml.Marshaler interface.

func (*ErrorGroup) Release

func (eg *ErrorGroup) Release()

Release returns the ErrorGroup to its pool if it came from one. If the ErrorGroup wasn't created from a pool, Release is a no-op.

func (*ErrorGroup) ToJSON added in v1.3.2

func (eg *ErrorGroup) ToJSON() (string, error)

ToJSON converts the ErrorGroup to JSON format.

func (*ErrorGroup) ToSerialization added in v1.3.2

func (eg *ErrorGroup) ToSerialization() ErrorGroupSerialization

ToSerialization converts the ErrorGroup to a serializable format.

func (*ErrorGroup) ToYAML added in v1.3.2

func (eg *ErrorGroup) ToYAML() (string, error)

ToYAML converts the ErrorGroup to YAML format.

type ErrorGroupPool

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

ErrorGroupPool manages a pool of ErrorGroup instances. By making this a separate type, we give users control over pool lifecycle and configuration while maintaining encapsulation.

func NewErrorGroupPool

func NewErrorGroupPool(initialCapacity int) *ErrorGroupPool

NewErrorGroupPool creates a new pool for error groups with the specified initial capacity for the error slices.

func (*ErrorGroupPool) Get

func (p *ErrorGroupPool) Get() *ErrorGroup

Get retrieves an ErrorGroup from the pool or creates a new one if the pool is empty.

type ErrorGroupSerialization added in v1.3.2

type ErrorGroupSerialization struct {
	ErrorCount int                 `json:"error_count" yaml:"error_count"`
	Timestamp  string              `json:"timestamp"   yaml:"timestamp"`
	Errors     []SerializableError `json:"errors"      yaml:"errors"`
}

ErrorGroupSerialization represents the serializable format of an ErrorGroup.

type ErrorOutput

type ErrorOutput struct {
	// Message contains the main error message
	Message string `json:"message"            yaml:"message"`
	// Timestamp indicates when the error occurred
	Timestamp string `json:"timestamp"          yaml:"timestamp"`
	// Type categorizes the error
	Type string `json:"type"               yaml:"type"`
	// Severity indicates the error's impact level
	Severity string `json:"severity"           yaml:"severity"`
	// Stack contains the error stack trace
	Stack string `json:"stack"              yaml:"stack"`
	// Cause contains the underlying error if any
	Cause *ErrorOutput `json:"cause,omitempty"    yaml:"cause,omitempty"`
	// Context contains additional error context
	Context map[string]any `json:"context,omitempty"  yaml:"context,omitempty"`
	// Metadata contains user-defined metadata
	Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
	// Recovery provides guidance on resolving the error
	Recovery *RecoverySuggestion `json:"recovery,omitempty" yaml:"recovery,omitempty"`
}

ErrorOutput represents a formatted error output structure that can be serialized to various formats like JSON and YAML.

type ErrorType

type ErrorType int

ErrorType represents the type of error that occurred.

const (
	// ErrorTypeUnknown represents an unknown error type.
	ErrorTypeUnknown ErrorType = iota
	// ErrorTypeValidation represents a validation error.
	ErrorTypeValidation
	// ErrorTypeNotFound represents a not found error.
	ErrorTypeNotFound
	// ErrorTypePermission represents a permission error.
	ErrorTypePermission
	// ErrorTypeDatabase represents a database error.
	ErrorTypeDatabase
	// ErrorTypeNetwork represents a network error.
	ErrorTypeNetwork
	// ErrorTypeConfiguration represents a configuration error.
	ErrorTypeConfiguration
	// ErrorTypeInternal indicates internal system errors.
	ErrorTypeInternal
	// ErrorTypeExternal indicates errors from external services.
	ErrorTypeExternal
)

func (ErrorType) String

func (et ErrorType) String() string

String returns the string representation of the error type, useful for logging and error reporting.

type FormatOption

type FormatOption func(*ErrorOutput)

FormatOption defines formatting options for error output.

func WithStackTrace

func WithStackTrace(include bool) FormatOption

WithStackTrace controls whether to include the stack trace in the output.

func WithTimestampFormat

func WithTimestampFormat(format string) FormatOption

WithTimestampFormat allows customizing the timestamp format in the output.

type Observer added in v1.3.0

type Observer interface {
	// RecordError is called when an error is logged.
	RecordError(message string)
	// RecordCircuitStateTransition is called when a circuit breaker changes state.
	RecordCircuitStateTransition(name string, from, to CircuitState)
}

Observer defines hooks for observing errors and circuit breaker state transitions.

type Option

type Option func(*Error)

Option defines the signature for configuration options.

func WithContext

func WithContext(ctx context.Context, errorType ErrorType, severity Severity) Option

WithContext adds context information to the error.

func WithLogger

func WithLogger(log logger.Logger) Option

WithLogger sets a logger for the error.

func WithObserver added in v1.3.2

func WithObserver(observer Observer) Option

WithObserver sets an observer for the error.

func WithRecoverySuggestion added in v1.3.0

func WithRecoverySuggestion(rs *RecoverySuggestion) Option

WithRecoverySuggestion attaches recovery guidance to the error.

func WithRetry

func WithRetry(maxAttempts int, delay time.Duration, opts ...RetryOption) Option

WithRetry adds retry information to the error.

type RecoverySuggestion

type RecoverySuggestion struct {
	// Message provides a human-readable explanation.
	Message string `json:"message"       yaml:"message"`
	// Actions lists specific steps that can be taken.
	Actions []string `json:"actions"       yaml:"actions"`
	// Documentation links to relevant documentation.
	Documentation string `json:"documentation" yaml:"documentation"`
}

RecoverySuggestion provides guidance on how to recover from an error.

type RetryInfo

type RetryInfo struct {
	// MaxAttempts is the maximum number of retry attempts.
	MaxAttempts int
	// CurrentAttempt is the current retry attempt.
	CurrentAttempt int
	// Delay is the delay between retry attempts.
	Delay time.Duration
	// LastAttempt is the timestamp of the last retry attempt.
	LastAttempt time.Time
	// ShouldRetry is a function that determines if a retry should be attempted.
	ShouldRetry func(error) bool
}

RetryInfo holds information about retry attempts.

type RetryOption added in v1.3.0

type RetryOption func(*RetryInfo)

RetryOption configures RetryInfo.

func WithRetryShould added in v1.3.0

func WithRetryShould(fn func(error) bool) RetryOption

WithRetryShould sets a custom ShouldRetry function.

type SerializableError added in v1.3.2

type SerializableError struct {
	Message    string             `json:"message"               yaml:"message"`
	Type       string             `json:"type"                  yaml:"type"`
	StackTrace []StackFrame       `json:"stack_trace,omitempty" yaml:"stack_trace,omitempty"`
	Metadata   map[string]any     `json:"metadata,omitempty"    yaml:"metadata,omitempty"`
	Cause      *SerializableError `json:"cause,omitempty"       yaml:"cause,omitempty"`
}

SerializableError represents an error in a serializable format.

type Severity

type Severity int

Severity represents the impact level of an error.

const (
	// SeverityInfo indicates an informational message.
	SeverityInfo Severity = iota
	// SeverityWarning indicates a warning that needs attention.
	SeverityWarning
	// SeverityError indicates a significant error.
	SeverityError
	// SeverityCritical indicates a critical system failure.
	SeverityCritical
)

func (Severity) String

func (s Severity) String() string

String returns the string representation of the severity level.

type StackFrame added in v1.3.2

type StackFrame struct {
	// Function is the fully qualified function name
	Function string `json:"function" yaml:"function"`
	// File is the source file path
	File string `json:"file"     yaml:"file"`
	// Line is the line number in the source file
	Line int `json:"line"     yaml:"line"`
	// PC is the program counter for this frame
	PC uintptr `json:"pc"       yaml:"pc"`
}

StackFrame represents a single frame in a stack trace.

type StackIterator added in v1.3.2

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

StackIterator provides a way to iterate through stack frames.

func NewStackIterator added in v1.3.2

func NewStackIterator(pcs []uintptr) *StackIterator

NewStackIterator creates a new stack iterator from program counters.

func (*StackIterator) AllFrames added in v1.3.2

func (si *StackIterator) AllFrames() []StackFrame

AllFrames returns all frames regardless of current position.

func (*StackIterator) Frames added in v1.3.2

func (si *StackIterator) Frames() []StackFrame

Frames returns all remaining frames as a slice.

func (*StackIterator) HasNext added in v1.3.2

func (si *StackIterator) HasNext() bool

HasNext returns true if there are more frames to iterate.

func (*StackIterator) Next added in v1.3.2

func (si *StackIterator) Next() *StackFrame

Next returns the next stack frame, or nil if no more frames.

func (*StackIterator) Reset added in v1.3.2

func (si *StackIterator) Reset()

Reset resets the iterator to the beginning.

type StackTrace added in v1.3.2

type StackTrace []StackFrame

StackTrace represents a collection of stack frames.

Directories

Path Synopsis
observer command
serialization command
internal
logger
Package logger provides a standardized logging interface for the application.
Package logger provides a standardized logging interface for the application.
pkg
logger/adapters
Package adapters provides logging adapters for popular logging frameworks
Package adapters provides logging adapters for popular logging frameworks

Jump to

Keyboard shortcuts

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