errors

package
v0.0.0-...-9a2a36c Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package errors provides helper functions for creating common structured errors.

Package errors provides structured error types and categorization for the commitgraph project.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetHTTPStatus

func GetHTTPStatus(err error) int

GetHTTPStatus returns the HTTP status code for an error, if applicable.

func IsHTTPClientError

func IsHTTPClientError(err error) bool

IsHTTPClientError returns true if the error is an HTTP 4xx client error.

func IsHTTPServerError

func IsHTTPServerError(err error) bool

IsHTTPServerError returns true if the error is an HTTP 5xx server error.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable returns true if the error is retryable.

Types

type ClassifyOptions

type ClassifyOptions struct {
	Component  string
	Operation  string
	StatusCode int
	Context    ErrorContext
}

ClassifyOptions provides options for error classification.

type ErrorCategory

type ErrorCategory string

ErrorCategory represents the type/category of an error.

const (
	// ValidationError indicates input validation failures
	ValidationError ErrorCategory = "validation_error"
	// ParseError indicates data parsing failures
	ParseError ErrorCategory = "parse_error"
	// DatabaseError indicates database operation failures
	DatabaseError ErrorCategory = "database_error"
	// NetworkError indicates network operation failures
	NetworkError ErrorCategory = "network_error"
	// TimeoutError indicates operation timeout failures
	TimeoutError ErrorCategory = "timeout_error"
	// ClientError indicates HTTP 4xx client errors
	ClientError ErrorCategory = "client_error"
	// ServerError indicates HTTP 5xx server errors
	ServerError ErrorCategory = "server_error"
	// AuthError indicates authentication/authorization failures
	AuthError ErrorCategory = "authentication_error"
	// ConfigError indicates configuration problems
	ConfigError ErrorCategory = "configuration_error"
	// ResourceError indicates resource exhaustion/unavailability
	ResourceError ErrorCategory = "resource_error"
	// ConcurrencyError indicates concurrency/locking issues
	ConcurrencyError ErrorCategory = "concurrency_error"
	// UnknownError indicates uncategorized errors
	UnknownError ErrorCategory = "unknown_error"
)

func GetType

func GetType(err error) ErrorCategory

GetType returns the error category of an error.

type ErrorContext

type ErrorContext struct {
	UserID     string            // User ID involved in the operation
	RequestID  string            // Request ID for tracing
	SessionID  string            // Session ID for context
	Endpoint   string            // API endpoint involved
	StatusCode int               // HTTP status code (if applicable)
	Query      string            // Database query (sanitized)
	Package    string            // Package/function where error occurred
	File       string            // File where error occurred
	Line       int               // Line number where error occurred
	Extra      map[string]string // Additional context
}

ErrorContext contains additional contextual information about an error.

type ErrorContextOption

type ErrorContextOption func(*StructuredError)

ErrorContextOption is a functional option for NewError that allows setting context fields.

func WithCommitSHAOption

func WithCommitSHAOption(commitSHA string) ErrorContextOption

WithCommitSHAOption creates an ErrorContextOption that sets the commit SHA.

func WithEmailOption

func WithEmailOption(email string) ErrorContextOption

WithEmailOption creates an ErrorContextOption that sets the email.

func WithPositionOption

func WithPositionOption(position int64) ErrorContextOption

WithPositionOption creates an ErrorContextOption that sets the position.

func WithRecordKeyOption

func WithRecordKeyOption(recordKey string) ErrorContextOption

WithRecordKeyOption creates an ErrorContextOption that sets the record key.

func WithTraceIDOption

func WithTraceIDOption(traceID string) ErrorContextOption

WithTraceIDOption creates an ErrorContextOption that sets the trace ID.

type RecoverySuggestion

type RecoverySuggestion struct {
	Action        string        // Human-readable recovery action
	Steps         []string      // Detailed recovery steps
	Documentation string        // Link to relevant documentation
	Severity      SeverityLevel // Recovery urgency
}

RecoverySuggestion provides actionable recovery suggestions for errors.

type RetryPolicy

type RetryPolicy struct {
	MaxRetries   int           // Maximum number of retry attempts
	InitialDelay time.Duration // Initial delay before first retry
	MaxDelay     time.Duration // Maximum delay between retries
	Multiplier   float64       // Backoff multiplier (for exponential backoff)
	Strategy     RetryStrategy // Retry strategy to use
}

RetryPolicy defines the retry policy for retryable errors.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns a default retry policy with exponential backoff.

type RetryStrategy

type RetryStrategy string

RetryStrategy represents the retry strategy for an error.

const (
	// RetryStrategyNone indicates no retry
	RetryStrategyNone RetryStrategy = "none"
	// RetryStrategyLinear indicates linear backoff
	RetryStrategyLinear RetryStrategy = "linear"
	// RetryStrategyExponential indicates exponential backoff
	RetryStrategyExponential RetryStrategy = "exponential"
)

type SeverityLevel

type SeverityLevel string

SeverityLevel represents the severity of an error.

const (
	// SeverityCritical indicates complete service failure requiring immediate intervention
	SeverityCritical SeverityLevel = "critical"
	// SeverityHigh indicates significant impact requiring prompt attention
	SeverityHigh SeverityLevel = "high"
	// SeverityMedium indicates limited impact with workarounds
	SeverityMedium SeverityLevel = "medium"
	// SeverityLow indicates minimal impact or edge cases
	SeverityLow SeverityLevel = "low"
	// SeverityInfo indicates informational events (not errors)
	SeverityInfo SeverityLevel = "info"
)

func GetSeverity

func GetSeverity(err error) SeverityLevel

GetSeverity returns the severity level of an error.

type StructuredError

type StructuredError struct {
	// Core error information
	Type     ErrorCategory // Categorized error type
	Severity SeverityLevel // Error severity level
	Message  string        // Human-readable error message
	Code     string        // Machine-readable error code

	// Context information
	Component string       // Component/package where error occurred
	Operation string       // Operation being performed
	Context   ErrorContext // Additional contextual information

	// Domain-specific context fields
	CommitSHA string // Commit SHA associated with the error
	Position  int64  // Position/offset in data stream
	Email     string // Email address involved in the error
	TraceID   string // Trace ID for distributed tracing
	RecordKey string // Record key for database/storage operations

	// Technical details
	Cause      error     // Underlying error (for wrapping)
	StackTrace string    // Stack trace at error site
	Timestamp  time.Time // When the error occurred

	// Retry/Recovery information
	Retryable   bool               // Whether this error is retryable
	RetryPolicy RetryPolicy        // Retry strategy if retryable
	Recovery    RecoverySuggestion // Suggested recovery actions

	// Additional metadata
	Metadata map[string]interface{} // Additional context
}

StructuredError is the main error type that wraps errors with comprehensive metadata.

func AuthErrorf

func AuthErrorf(component, operation, format string, args ...interface{}) *StructuredError

AuthErrorf creates an authentication/authorization error.

func ClassifyError

func ClassifyError(err error, opts ClassifyOptions) *StructuredError

ClassifyError classifies an error and creates a StructuredError with appropriate metadata.

func ConcurrencyErrorf

func ConcurrencyErrorf(component, operation, format string, args ...interface{}) *StructuredError

ConcurrencyErrorf creates a concurrency error with formatted message.

func ConfigErrorf

func ConfigErrorf(component, format string, args ...interface{}) *StructuredError

ConfigErrorf creates a configuration error with formatted message.

func ConnectionPoolExhaustedError

func ConnectionPoolExhaustedError(component, operation, poolName string) *StructuredError

ConnectionPoolExhaustedError creates a connection pool exhaustion error.

func ConnectionRefusedError

func ConnectionRefusedError(component, operation, endpoint string) *StructuredError

ConnectionRefusedError creates a connection refused error.

func DNSError

func DNSError(component, operation, hostname string) *StructuredError

DNSError creates a DNS resolution error.

func DatabaseConnectionError

func DatabaseConnectionError(component, operation, dataSource string) *StructuredError

DatabaseConnectionError creates a database connection error.

func DatabaseErrorf

func DatabaseErrorf(component, operation, query, format string, args ...interface{}) *StructuredError

DatabaseErrorf creates a database error with formatted message.

func DatabaseQueryError

func DatabaseQueryError(component, operation, query, reason string) *StructuredError

DatabaseQueryError creates a database query execution error.

func DatabaseTimeoutError

func DatabaseTimeoutError(component, operation, query string, timeoutSeconds int) *StructuredError

DatabaseTimeoutError creates a database timeout error.

func DeadlockError

func DeadlockError(component, operation, resource string) *StructuredError

DeadlockError creates a deadlock detection error.

func DiskSpaceExhaustedError

func DiskSpaceExhaustedError(component, operation, path string) *StructuredError

DiskSpaceExhaustedError creates a disk space exhaustion error.

func ForbiddenError

func ForbiddenError(component, operation, resource string) *StructuredError

ForbiddenError creates a 403 Forbidden error.

func HTTPError

func HTTPError(component, operation, url string, statusCode int, responseBody string) *StructuredError

HTTPError creates an HTTP error based on status code.

func HTTPTimeoutError

func HTTPTimeoutError(component, operation, url string, timeoutSeconds int) *StructuredError

HTTPTimeoutError creates an HTTP timeout error.

func InvalidConfigError

func InvalidConfigError(component, configKey, reason string) *StructuredError

InvalidConfigError creates an error for invalid configuration values.

func InvalidFormatError

func InvalidFormatError(component, operation, field, expectedFormat string) *StructuredError

InvalidFormatError creates an error for invalid field formats.

func JSONParseError

func JSONParseError(component, operation string) *StructuredError

JSONParseError creates an error for JSON parsing failures. Deprecated: Use JSONParseErrorWithCommit to include commit SHA context.

func JSONParseErrorWithCommit

func JSONParseErrorWithCommit(component, operation, commitSHA string) *StructuredError

JSONParseErrorWithCommit creates an error for JSON parsing failures with commit SHA.

func LockConflictError

func LockConflictError(component, operation, resource string) *StructuredError

LockConflictError creates a lock conflict error.

func MemoryExhaustedError

func MemoryExhaustedError(component, operation string) *StructuredError

MemoryExhaustedError creates a memory exhaustion error.

func MissingConfigError

func MissingConfigError(component, configKey string) *StructuredError

MissingConfigError creates an error for missing configuration values.

func NetworkErrorf

func NetworkErrorf(component, operation, endpoint, format string, args ...interface{}) *StructuredError

NetworkErrorf creates a network error with formatted message.

func NewError

func NewError(typ ErrorCategory, severity SeverityLevel, message, code, component, operation string, opts ...ErrorContextOption) *StructuredError

NewError creates a new structured error with the given parameters and optional context.

func ParseErrorf

func ParseErrorf(component, operation, dataType, format string, args ...interface{}) *StructuredError

ParseErrorf creates a parse error with formatted message. Deprecated: Use ParseErrorfWithCommit to include commit SHA context.

func ParseErrorfWithCommit

func ParseErrorfWithCommit(component, operation, dataType, commitSHA, format string, args ...interface{}) *StructuredError

ParseErrorfWithCommit creates a parse error with formatted message and commit SHA.

func RequiredFieldError

func RequiredFieldError(component, operation, field string) *StructuredError

RequiredFieldError creates an error for missing required fields.

func ResourceErrorf

func ResourceErrorf(component, operation, resourceType, format string, args ...interface{}) *StructuredError

ResourceErrorf creates a resource error with formatted message.

func TimeoutErrorf

func TimeoutErrorf(component, operation, target, format string, args ...interface{}) *StructuredError

TimeoutErrorf creates a timeout error with formatted message.

func TokenExpiredError

func TokenExpiredError(component, operation string) *StructuredError

TokenExpiredError creates a token expiration error.

func UnauthorizedError

func UnauthorizedError(component, operation string) *StructuredError

UnauthorizedError creates a 401 Unauthorized error.

func ValidationErrorf

func ValidationErrorf(component, operation, field, format string, args ...interface{}) *StructuredError

ValidationErrorf creates a validation error with formatted message.

func WrapError

func WrapError(cause error, base StructuredError) *StructuredError

WrapError wraps an existing error with additional context and structured information.

func (*StructuredError) Error

func (e *StructuredError) Error() string

Error implements the error interface for StructuredError.

func (*StructuredError) ErrorCode

func (e *StructuredError) ErrorCode() string

ErrorCode returns the machine-readable error code.

func (*StructuredError) GetType

func (e *StructuredError) GetType() ErrorCategory

GetType returns the error category.

func (*StructuredError) IsRetryable

func (e *StructuredError) IsRetryable() bool

IsRetryable returns whether the error is retryable.

func (*StructuredError) SeverityCode

func (e *StructuredError) SeverityCode() SeverityLevel

SeverityCode returns the severity level.

func (*StructuredError) Unwrap

func (e *StructuredError) Unwrap() error

Unwrap returns the underlying error for error wrapping chains.

func (*StructuredError) WithCommitSHA

func (e *StructuredError) WithCommitSHA(commitSHA string) *StructuredError

WithCommitSHA sets the commit SHA context on the error.

func (*StructuredError) WithContext

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

WithContext adds context information to the error.

func (*StructuredError) WithEmail

func (e *StructuredError) WithEmail(email string) *StructuredError

WithEmail sets the email context on the error.

func (*StructuredError) WithMetadata

func (e *StructuredError) WithMetadata(metadata map[string]interface{}) *StructuredError

WithMetadata adds metadata to the error.

func (*StructuredError) WithPosition

func (e *StructuredError) WithPosition(position int64) *StructuredError

WithPosition sets the position context on the error.

func (*StructuredError) WithRecordKey

func (e *StructuredError) WithRecordKey(recordKey string) *StructuredError

WithRecordKey sets the record key context on the error.

func (*StructuredError) WithRecovery

func (e *StructuredError) WithRecovery(recovery RecoverySuggestion) *StructuredError

WithRecovery sets the recovery suggestion for the error.

func (*StructuredError) WithRetryPolicy

func (e *StructuredError) WithRetryPolicy(policy RetryPolicy) *StructuredError

WithRetryPolicy sets the retry policy for the error.

func (*StructuredError) WithTraceID

func (e *StructuredError) WithTraceID(traceID string) *StructuredError

WithTraceID sets the trace ID context on the error.

Jump to

Keyboard shortcuts

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