errors

package
v0.0.0-...-1c48c90 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package errors provides advanced error handling and recovery capabilities. This includes retry logic, panic recovery, error categorization, and context-aware error management.

Package errors provides standardized error handling patterns and utilities for consistent error management across the application.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrConfigNotFound indicates that configuration could not be located.
	ErrConfigNotFound = sterrors.New("config not found")
	// ErrInvalidConfig indicates the provided configuration is invalid.
	ErrInvalidConfig = sterrors.New("invalid config")
	// ErrConfigNotLoaded indicates no configuration has been loaded.
	ErrConfigNotLoaded = sterrors.New("no configuration loaded")
)

Functions

func GetMemoryStats

func GetMemoryStats() map[string]interface{}

GetMemoryStats returns current memory statistics.

func Wrap

func Wrap(err, target error) error

Wrap annotates err with target to allow errors.Is/As checks on target while preserving the original error as the cause.

Types

type CircuitBreaker

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

CircuitBreaker implements a simple circuit breaker pattern.

func NewCircuitBreaker

func NewCircuitBreaker(maxFailures int, resetTime time.Duration) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker.

func (*CircuitBreaker) Execute

func (cb *CircuitBreaker) Execute(fn func() error) error

Execute executes a function through the circuit breaker.

func (*CircuitBreaker) GetState

func (cb *CircuitBreaker) GetState() CircuitState

GetState returns the current state of the circuit breaker.

type CircuitState

type CircuitState int

CircuitState represents the state of a circuit breaker.

const (
	// StateClosed represents a closed circuit breaker state.
	StateClosed CircuitState = iota
	// StateOpen represents an open circuit breaker state.
	StateOpen
	// StateHalfOpen represents a half-open circuit breaker state.
	StateHalfOpen
)

func (CircuitState) String

func (s CircuitState) String() string

type ErrorCode

type ErrorCode string

ErrorCode represents standardized error codes for consistent error classification.

const (
	// ErrorCodeInvalidConfig indicates invalid configuration data.
	ErrorCodeInvalidConfig ErrorCode = "INVALID_CONFIG"
	// ErrorCodeMissingConfig indicates missing required configuration.
	ErrorCodeMissingConfig ErrorCode = "MISSING_CONFIG"
	// ErrorCodeConfigNotFound indicates configuration file not found.
	ErrorCodeConfigNotFound ErrorCode = "CONFIG_NOT_FOUND"

	// ErrorCodeInvalidToken indicates an invalid authentication token.
	ErrorCodeInvalidToken ErrorCode = "INVALID_TOKEN"
	// ErrorCodeTokenExpired indicates an expired authentication token.
	ErrorCodeTokenExpired ErrorCode = "TOKEN_EXPIRED"
	// ErrorCodeInsufficientPerms indicates insufficient permissions.
	ErrorCodeInsufficientPerms ErrorCode = "INSUFFICIENT_PERMISSIONS"
	// ErrorCodeAuthFailed indicates authentication failure.
	ErrorCodeAuthFailed ErrorCode = "AUTHENTICATION_FAILED"

	// ErrorCodeNetworkTimeout indicates a network timeout occurred.
	ErrorCodeNetworkTimeout ErrorCode = "NETWORK_TIMEOUT"
	// ErrorCodeConnectionFailed indicates connection failure.
	ErrorCodeConnectionFailed ErrorCode = "CONNECTION_FAILED"
	// ErrorCodeRateLimitExceeded indicates API rate limit exceeded.
	ErrorCodeRateLimitExceeded ErrorCode = "RATE_LIMIT_EXCEEDED"
	// ErrorCodeAPIUnavailable indicates API is unavailable.
	ErrorCodeAPIUnavailable ErrorCode = "API_UNAVAILABLE"

	// ErrorCodeRepoNotFound indicates repository not found.
	ErrorCodeRepoNotFound ErrorCode = "REPOSITORY_NOT_FOUND"
	// ErrorCodeCloneFailed indicates repository clone failure.
	ErrorCodeCloneFailed ErrorCode = "CLONE_FAILED"
	// ErrorCodeGitOperationFailed indicates git operation failure.
	ErrorCodeGitOperationFailed ErrorCode = "GIT_OPERATION_FAILED"
	// ErrorCodePermissionDenied indicates permission denied.
	ErrorCodePermissionDenied ErrorCode = "PERMISSION_DENIED"

	// ErrorCodeInvalidInput indicates invalid input data.
	ErrorCodeInvalidInput ErrorCode = "INVALID_INPUT"
	// ErrorCodeValidationFailed indicates validation failure.
	ErrorCodeValidationFailed ErrorCode = "VALIDATION_FAILED"
	// ErrorCodeInvalidFormat indicates invalid format.
	ErrorCodeInvalidFormat ErrorCode = "INVALID_FORMAT"

	// ErrorCodeInternalError indicates internal system error.
	ErrorCodeInternalError ErrorCode = "INTERNAL_ERROR"
	// ErrorCodeResourceExhausted indicates resources exhausted.
	ErrorCodeResourceExhausted ErrorCode = "RESOURCE_EXHAUSTED"
	// ErrorCodeOperationFailed indicates operation failure.
	ErrorCodeOperationFailed ErrorCode = "OPERATION_FAILED"
	// ErrorCodeTimeout indicates operation timeout.
	ErrorCodeTimeout ErrorCode = "TIMEOUT"

	// ErrorCodeFileNotFound indicates file not found.
	ErrorCodeFileNotFound ErrorCode = "FILE_NOT_FOUND"
	// ErrorCodeAccessDenied indicates access denied.
	ErrorCodeAccessDenied ErrorCode = "ACCESS_DENIED"
	// ErrorCodeDiskFull indicates disk full.
	ErrorCodeDiskFull ErrorCode = "DISK_FULL"
	// ErrorCodeIOError indicates I/O error.
	ErrorCodeIOError ErrorCode = "IO_ERROR"
)

type ErrorCollector

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

ErrorCollector collects multiple errors for batch processing.

func NewErrorCollector

func NewErrorCollector() *ErrorCollector

NewErrorCollector creates a new error collector.

func (*ErrorCollector) AddError

func (ec *ErrorCollector) AddError(err *StandardError)

AddError adds an error to the collector.

func (*ErrorCollector) GetErrors

func (ec *ErrorCollector) GetErrors() []*StandardError

GetErrors returns all collected errors.

func (*ErrorCollector) GetWarnings

func (ec *ErrorCollector) GetWarnings() []*StandardError

GetWarnings returns all collected warnings.

func (*ErrorCollector) HasErrors

func (ec *ErrorCollector) HasErrors() bool

HasErrors returns true if there are any errors.

func (*ErrorCollector) HasWarnings

func (ec *ErrorCollector) HasWarnings() bool

HasWarnings returns true if there are any warnings.

func (*ErrorCollector) ToError

func (ec *ErrorCollector) ToError() error

ToError converts the collector to a single error if there are errors.

type ErrorFilter

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

ErrorFilter provides filtering capabilities for errors.

func NewErrorFilter

func NewErrorFilter() *ErrorFilter

NewErrorFilter creates a new error filter.

func (*ErrorFilter) Matches

func (ef *ErrorFilter) Matches(err *StandardError) bool

Matches returns true if the error matches the filter criteria.

func (*ErrorFilter) WithCodes

func (ef *ErrorFilter) WithCodes(codes ...ErrorCode) *ErrorFilter

WithCodes filters by error codes.

func (*ErrorFilter) WithRetryable

func (ef *ErrorFilter) WithRetryable(retryable bool) *ErrorFilter

WithRetryable filters by retryable status.

func (*ErrorFilter) WithSeverities

func (ef *ErrorFilter) WithSeverities(severities ...ErrorSeverity) *ErrorFilter

WithSeverities filters by severities.

type ErrorRecovery

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

ErrorRecovery provides advanced error handling and recovery capabilities.

func NewErrorRecovery

func NewErrorRecovery(config RecoveryConfig) *ErrorRecovery

NewErrorRecovery creates a new error recovery system.

func (*ErrorRecovery) Execute

func (er *ErrorRecovery) Execute(ctx context.Context, operation string, fn func() error) error

Execute runs a function with automatic retry and recovery.

func (*ErrorRecovery) ExecuteWithResult

func (er *ErrorRecovery) ExecuteWithResult(ctx context.Context, operation string, fn func() (interface{}, error)) error

ExecuteWithResult runs a function with return value and automatic retry.

func (*ErrorRecovery) RecoverPanic

func (er *ErrorRecovery) RecoverPanic()

RecoverPanic recovers from panics and converts them to errors.

func (*ErrorRecovery) WithPanicRecovery

func (er *ErrorRecovery) WithPanicRecovery(fn func()) (err error)

WithPanicRecovery wraps a function with panic recovery.

type ErrorSeverity

type ErrorSeverity string

ErrorSeverity represents the severity level of an error.

const (
	// SeverityLow indicates low severity error.
	SeverityLow ErrorSeverity = "low"
	// SeverityMedium indicates medium severity error.
	SeverityMedium ErrorSeverity = "medium"
	// SeverityHigh indicates high severity error.
	SeverityHigh ErrorSeverity = "high"
	// SeverityCritical indicates critical severity error.
	SeverityCritical ErrorSeverity = "critical"
)

Error severity levels.

type ErrorType

type ErrorType string

ErrorType represents different types of errors.

const (
	// ErrorTypeNetwork represents network-related errors.
	ErrorTypeNetwork ErrorType = "network"
	// ErrorTypeAuth represents authentication-related errors.
	ErrorTypeAuth ErrorType = "auth"
	// ErrorTypeValidation represents validation-related errors.
	ErrorTypeValidation ErrorType = "validation"
	// ErrorTypeSystem represents system-related errors.
	ErrorTypeSystem ErrorType = "system"
	// ErrorTypeTimeout represents timeout-related errors.
	ErrorTypeTimeout ErrorType = "timeout"
	// ErrorTypeRateLimit represents rate limit-related errors.
	ErrorTypeRateLimit ErrorType = "rate_limit"
	// ErrorTypeUnknown represents unknown error types.
	ErrorTypeUnknown ErrorType = "unknown"
)

type HealthCheck

type HealthCheck struct {
	Name        string
	Description string
	CheckFunc   func() error
	Timeout     time.Duration
}

HealthCheck represents a system health check.

type HealthMonitor

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

HealthMonitor monitors system health.

func NewHealthMonitor

func NewHealthMonitor(logger Logger) *HealthMonitor

NewHealthMonitor creates a new health monitor.

func (*HealthMonitor) AddCheck

func (hm *HealthMonitor) AddCheck(check HealthCheck)

AddCheck adds a health check.

func (*HealthMonitor) RunChecks

func (hm *HealthMonitor) RunChecks(ctx context.Context) map[string]error

RunChecks runs all health checks.

type Logger

type Logger interface {
	Error(msg string, args ...interface{})
	Warn(msg string, args ...interface{})
	Info(msg string, args ...interface{})
	Debug(msg string, args ...interface{})
}

Logger interface for error recovery.

type RecoverableError

type RecoverableError struct {
	Type       ErrorType
	Message    string
	Cause      error
	Retryable  bool
	Context    map[string]interface{}
	StackTrace string
	Timestamp  time.Time
}

RecoverableError represents an error that can be recovered from.

func NewRecoverableError

func NewRecoverableError(errType ErrorType, message string, cause error, retryable bool) *RecoverableError

NewRecoverableError creates a new recoverable error.

func (*RecoverableError) Error

func (e *RecoverableError) Error() string

func (*RecoverableError) IsRetryable

func (e *RecoverableError) IsRetryable() bool

IsRetryable returns whether the error can be retried.

func (*RecoverableError) Unwrap

func (e *RecoverableError) Unwrap() error

func (*RecoverableError) WithContext

func (e *RecoverableError) WithContext(key string, value interface{}) *RecoverableError

WithContext adds context to the error.

type RecoveryConfig

type RecoveryConfig struct {
	MaxRetries       int
	RetryDelay       time.Duration
	CircuitThreshold int
	ResetTimeout     time.Duration
	Logger           Logger
	RecoveryFunc     func(error) error
}

RecoveryConfig configures error recovery behavior.

type StandardError

type StandardError struct {
	Code        ErrorCode              `json:"code"`
	Message     string                 `json:"message"`
	Severity    ErrorSeverity          `json:"severity"`
	Timestamp   time.Time              `json:"timestamp"`
	Context     map[string]interface{} `json:"context,omitempty"`
	Cause       error                  `json:"cause,omitempty"`
	StackTrace  string                 `json:"stackTrace,omitempty"`
	Suggestions []string               `json:"suggestions,omitempty"`
	Retryable   bool                   `json:"retryable"`
}

StandardError represents a standardized error with context and metadata.

func NewAuthError

func NewAuthError(message string, cause error) *StandardError

NewAuthError creates an authentication-related error.

func NewConfigError

func NewConfigError(message string, cause error) *StandardError

NewConfigError creates a configuration-related error.

func NewFileSystemError

func NewFileSystemError(message, path string, cause error) *StandardError

NewFileSystemError creates a file system-related error.

func NewNetworkError

func NewNetworkError(message string, cause error) *StandardError

NewNetworkError creates a network-related error.

func NewRepositoryError

func NewRepositoryError(message, repository string, cause error) *StandardError

NewRepositoryError creates a repository-related error.

func NewStandardError

func NewStandardError(code ErrorCode, message string, severity ErrorSeverity) *StandardError

NewStandardError creates a new standardized error.

func NewValidationError

func NewValidationError(message, field string) *StandardError

NewValidationError creates a validation-related error.

func WrapError

func WrapError(cause error, code ErrorCode, message string, severity ErrorSeverity) *StandardError

WrapError wraps an existing error with standardized error context.

func (*StandardError) Error

func (e *StandardError) Error() string

Error implements the error interface.

func (*StandardError) Is

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

Is implements error comparison for errors.Is().

func (*StandardError) Unwrap

func (e *StandardError) Unwrap() error

Unwrap returns the underlying cause for error unwrapping.

func (*StandardError) WithContext

func (e *StandardError) WithContext(key string, value interface{}) *StandardError

WithContext adds context information to the error.

func (*StandardError) WithRetryable

func (e *StandardError) WithRetryable(retryable bool) *StandardError

WithRetryable sets whether the error should be retried.

func (*StandardError) WithSuggestion

func (e *StandardError) WithSuggestion(suggestion string) *StandardError

WithSuggestion adds a suggestion for resolving the error.

Jump to

Keyboard shortcuts

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