errors

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2025 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package errors provides structured error handling for Typosentinel This package implements comprehensive error types with context and categorization

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetHTTPStatus

func GetHTTPStatus(err error) int

GetHTTPStatus returns the appropriate HTTP status code for an error

func HasCode

func HasCode(err error, code ErrorCode) bool

HasCode checks if an error has a specific error code

func IsAppError

func IsAppError(err error) bool

IsAppError checks if an error is an AppError

func IsRetryable

func IsRetryable(err error) bool

IsRetryable checks if an error is retryable

Types

type AppError

type AppError struct {
	Code       ErrorCode              `json:"code"`
	Message    string                 `json:"message"`
	Cause      error                  `json:"-"`
	Context    map[string]interface{} `json:"context,omitempty"`
	Severity   Severity               `json:"severity"`
	Timestamp  time.Time              `json:"timestamp"`
	StackTrace string                 `json:"stack_trace,omitempty"`
	RequestID  string                 `json:"request_id,omitempty"`
	UserID     string                 `json:"user_id,omitempty"`
	Retryable  bool                   `json:"retryable"`
}

AppError represents a structured application error

func GetAppError

func GetAppError(err error) *AppError

GetAppError extracts an AppError from an error chain

func New

func New(code ErrorCode, message string) *AppError

New creates a new AppError

func NewAlreadyExistsError

func NewAlreadyExistsError(resource, id string) *AppError

func NewAppError

func NewAppError(code ErrorCode, message string) *AppError

NewAppError creates a new AppError with the given code and message

func NewConfigError

func NewConfigError(key, reason string) *AppError

Configuration error constructors

func NewDatabaseError

func NewDatabaseError(operation string, err error) *AppError

Database error constructors

func NewForbiddenError

func NewForbiddenError(resource string) *AppError

func NewInternalError

func NewInternalError(message string) *AppError

Internal error constructors

func NewInvalidInputError

func NewInvalidInputError(field, value string) *AppError

func NewMissingRequiredError

func NewMissingRequiredError(field string) *AppError

func NewNetworkError

func NewNetworkError(message string) *AppError

Network error constructors

func NewNotFoundError

func NewNotFoundError(resource, id string) *AppError

Resource error constructors

func NewPanicError

func NewPanicError(recovered interface{}) *AppError

func NewParsingError

func NewParsingError(format, input string) *AppError

func NewProcessingError

func NewProcessingError(message string) *AppError

Processing error constructors

func NewRateLimitError

func NewRateLimitError(limit int, window time.Duration) *AppError

func NewTimeoutError

func NewTimeoutError(operation string, timeout time.Duration) *AppError

func NewUnauthorizedError

func NewUnauthorizedError(message string) *AppError

Authentication error constructors

func NewValidationError

func NewValidationError(message string) *AppError

Validation error constructors

func Newf

func Newf(code ErrorCode, format string, args ...interface{}) *AppError

Newf creates a new AppError with formatted message

func Wrap

func Wrap(err error, code ErrorCode, message string) *AppError

Wrap wraps an existing error with additional context

func Wrapf

func Wrapf(err error, code ErrorCode, format string, args ...interface{}) *AppError

Wrapf wraps an existing error with formatted message

func (*AppError) Error

func (e *AppError) Error() string

Error implements the error interface

func (*AppError) GetCode

func (e *AppError) GetCode() ErrorCode

GetCode returns the error code

func (*AppError) GetSeverity

func (e *AppError) GetSeverity() Severity

GetSeverity returns the error severity

func (*AppError) Is

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

Is checks if the error matches the target error

func (*AppError) IsRetryable

func (e *AppError) IsRetryable() bool

IsRetryable returns whether the error is retryable

func (*AppError) Unwrap

func (e *AppError) Unwrap() error

Unwrap returns the underlying cause error

func (*AppError) WithContext

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

WithContext adds context information to the error

func (*AppError) WithRequestID

func (e *AppError) WithRequestID(requestID string) *AppError

WithRequestID adds a request ID to the error

func (*AppError) WithUserID

func (e *AppError) WithUserID(userID string) *AppError

WithUserID adds a user ID to the error

type EnhancedError

type EnhancedError struct {
	// Core error information
	Code     string
	Message  string
	Category ErrorCategory
	Severity ErrorSeverity
	Cause    error
	Context  map[string]interface{}

	// User-friendly information
	UserMessage   string
	Explanation   string
	Suggestions   []string
	Documentation string
	Examples      []string

	// Technical details
	StackTrace string
	Timestamp  string
	Component  string
}

EnhancedError provides user-friendly error messages with context and suggestions

func ErrConfigFileNotFound

func ErrConfigFileNotFound(path string) *EnhancedError

ErrConfigFileNotFound creates a config file not found error

func ErrDependencyNotFound

func ErrDependencyNotFound(dependency string) *EnhancedError

ErrDependencyNotFound creates a dependency not found error

func ErrInvalidConfiguration

func ErrInvalidConfiguration(field string, value interface{}) *EnhancedError

ErrInvalidConfiguration creates an invalid configuration error

func ErrNetworkTimeout

func ErrNetworkTimeout(url string) *EnhancedError

ErrNetworkTimeout creates a network timeout error

func ErrPermissionDenied

func ErrPermissionDenied(path string) *EnhancedError

ErrPermissionDenied creates a permission denied error

func (*EnhancedError) Error

func (e *EnhancedError) Error() string

Error implements the error interface

func (*EnhancedError) Unwrap

func (e *EnhancedError) Unwrap() error

Unwrap returns the underlying error

type ErrorBuilder

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

ErrorBuilder helps build enhanced errors

func ConfigurationError

func ConfigurationError(code, message string) *ErrorBuilder

ConfigurationError creates a configuration-related error

func DependencyError

func DependencyError(code, message string) *ErrorBuilder

DependencyError creates a dependency-related error

func NetworkError

func NetworkError(code, message string) *ErrorBuilder

NetworkError creates a network-related error

func NewError

func NewError(code, message string) *ErrorBuilder

NewError creates a new error builder

func PermissionError

func PermissionError(code, message string) *ErrorBuilder

PermissionError creates a permission-related error

func UsageError

func UsageError(code, message string) *ErrorBuilder

UsageError creates a usage-related error

func ValidationError

func ValidationError(code, message string) *ErrorBuilder

ValidationError creates a validation-related error

func (*ErrorBuilder) Build

func (b *ErrorBuilder) Build() *EnhancedError

Build returns the enhanced error

func (*ErrorBuilder) Category

func (b *ErrorBuilder) Category(category ErrorCategory) *ErrorBuilder

Category sets the error category

func (*ErrorBuilder) Cause

func (b *ErrorBuilder) Cause(cause error) *ErrorBuilder

Cause sets the underlying cause

func (*ErrorBuilder) Component

func (b *ErrorBuilder) Component(component string) *ErrorBuilder

Component sets the component name

func (*ErrorBuilder) Context

func (b *ErrorBuilder) Context(key string, value interface{}) *ErrorBuilder

Context adds context information

func (*ErrorBuilder) Documentation

func (b *ErrorBuilder) Documentation(url string) *ErrorBuilder

Documentation sets the documentation link

func (*ErrorBuilder) Example

func (b *ErrorBuilder) Example(example string) *ErrorBuilder

Example adds an example

func (*ErrorBuilder) Explanation

func (b *ErrorBuilder) Explanation(explanation string) *ErrorBuilder

Explanation sets the explanation

func (*ErrorBuilder) Severity

func (b *ErrorBuilder) Severity(severity ErrorSeverity) *ErrorBuilder

Severity sets the error severity

func (*ErrorBuilder) Suggestion

func (b *ErrorBuilder) Suggestion(suggestion string) *ErrorBuilder

Suggestion adds a suggestion

func (*ErrorBuilder) Suggestions

func (b *ErrorBuilder) Suggestions(suggestions ...string) *ErrorBuilder

Suggestions sets multiple suggestions

func (*ErrorBuilder) UserMessage

func (b *ErrorBuilder) UserMessage(message string) *ErrorBuilder

UserMessage sets the user-friendly message

type ErrorCategory

type ErrorCategory string

ErrorCategory represents different types of errors

const (
	CategoryConfiguration ErrorCategory = "configuration"
	CategoryNetwork       ErrorCategory = "network"
	CategoryPermission    ErrorCategory = "permission"
	CategoryDependency    ErrorCategory = "dependency"
	CategoryValidation    ErrorCategory = "validation"
	CategoryInternal      ErrorCategory = "internal"
	CategoryUsage         ErrorCategory = "usage"
)

type ErrorCode

type ErrorCode string

ErrorCode represents different categories of errors

const (
	// General errors
	INTERNAL_ERROR   ErrorCode = "INTERNAL_ERROR"
	INVALID_INPUT    ErrorCode = "INVALID_INPUT"
	UNAUTHORIZED     ErrorCode = "UNAUTHORIZED"
	FORBIDDEN        ErrorCode = "FORBIDDEN"
	RATE_LIMITED     ErrorCode = "RATE_LIMITED"
	NOT_FOUND_ERROR  ErrorCode = "NOT_FOUND_ERROR"
	VALIDATION_ERROR ErrorCode = "VALIDATION_ERROR"

	// Package scanning errors
	PACKAGE_NOT_FOUND ErrorCode = "PACKAGE_NOT_FOUND"
	SCAN_FAILED       ErrorCode = "SCAN_FAILED"
	INVALID_PACKAGE   ErrorCode = "INVALID_PACKAGE"

	// Database errors
	DB_CONNECTION_ERROR  ErrorCode = "DB_CONNECTION_ERROR"
	DB_QUERY_ERROR       ErrorCode = "DB_QUERY_ERROR"
	DB_TRANSACTION_ERROR ErrorCode = "DB_TRANSACTION_ERROR"

	// Cache errors
	CACHE_ERROR ErrorCode = "CACHE_ERROR"
	CACHE_MISS  ErrorCode = "CACHE_MISS"

	// ML/AI errors
	ML_MODEL_ERROR      ErrorCode = "ML_MODEL_ERROR"
	ML_PREDICTION_ERROR ErrorCode = "ML_PREDICTION_ERROR"

	// Configuration errors
	CONFIG_ERROR            ErrorCode = "CONFIG_ERROR"
	CONFIG_VALIDATION_ERROR ErrorCode = "CONFIG_VALIDATION_ERROR"

	// Input validation errors
	ErrCodeValidation      ErrorCode = "VALIDATION_ERROR"
	ErrCodeInvalidInput    ErrorCode = "INVALID_INPUT"
	ErrCodeMissingRequired ErrorCode = "MISSING_REQUIRED"

	// Network and external service errors
	ErrCodeNetwork            ErrorCode = "NETWORK_ERROR"
	ErrCodeTimeout            ErrorCode = "TIMEOUT_ERROR"
	ErrCodeRateLimit          ErrorCode = "RATE_LIMIT_ERROR"
	ErrCodeServiceUnavailable ErrorCode = "SERVICE_UNAVAILABLE"

	// Resource errors
	ErrCodeNotFound         ErrorCode = "NOT_FOUND"
	ErrCodeAlreadyExists    ErrorCode = "ALREADY_EXISTS"
	ErrCodePermissionDenied ErrorCode = "PERMISSION_DENIED"
	ErrCodeQuotaExceeded    ErrorCode = "QUOTA_EXCEEDED"

	// Processing errors
	ErrCodeProcessing ErrorCode = "PROCESSING_ERROR"
	ErrCodeParsing    ErrorCode = "PARSING_ERROR"
	ErrCodeEncoding   ErrorCode = "ENCODING_ERROR"
	ErrCodeDecoding   ErrorCode = "DECODING_ERROR"

	// Database errors
	ErrCodeDatabase    ErrorCode = "DATABASE_ERROR"
	ErrCodeTransaction ErrorCode = "TRANSACTION_ERROR"
	ErrCodeConstraint  ErrorCode = "CONSTRAINT_ERROR"

	// Authentication and authorization errors
	ErrCodeAuth         ErrorCode = "AUTH_ERROR"
	ErrCodeUnauthorized ErrorCode = "UNAUTHORIZED"
	ErrCodeForbidden    ErrorCode = "FORBIDDEN"
	ErrCodeTokenExpired ErrorCode = "TOKEN_EXPIRED"

	// Configuration errors
	ErrCodeConfig        ErrorCode = "CONFIG_ERROR"
	ErrCodeMissingConfig ErrorCode = "MISSING_CONFIG"
	ErrCodeInvalidConfig ErrorCode = "INVALID_CONFIG"

	// Internal system errors
	ErrCodeInternal ErrorCode = "INTERNAL_ERROR"
	ErrCodePanic    ErrorCode = "PANIC_ERROR"
	ErrCodeUnknown  ErrorCode = "UNKNOWN_ERROR"
)

type ErrorFormatter

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

ErrorFormatter handles formatting of enhanced errors for different outputs

func NewErrorFormatter

func NewErrorFormatter(colorEnabled, verboseMode bool) *ErrorFormatter

NewErrorFormatter creates a new error formatter

func (*ErrorFormatter) Format

func (f *ErrorFormatter) Format(err *EnhancedError) string

Format formats an enhanced error for display

type ErrorList

type ErrorList struct {
	Errors []*AppError `json:"errors"`
}

ErrorList represents a collection of errors

func NewErrorList

func NewErrorList() *ErrorList

NewErrorList creates a new error list

func (*ErrorList) Add

func (el *ErrorList) Add(err *AppError)

Add adds an error to the list

func (*ErrorList) AddError

func (el *ErrorList) AddError(err error)

AddError adds a generic error to the list

func (*ErrorList) Clear

func (el *ErrorList) Clear()

Clear removes all errors from the list

func (*ErrorList) Count

func (el *ErrorList) Count() int

Count returns the number of errors

func (*ErrorList) Error

func (el *ErrorList) Error() string

Error implements the error interface

func (*ErrorList) First

func (el *ErrorList) First() *AppError

First returns the first error in the list

func (*ErrorList) HasErrors

func (el *ErrorList) HasErrors() bool

HasErrors returns true if the list contains errors

type ErrorSeverity

type ErrorSeverity string

ErrorSeverity represents the severity level of an error

const (
	ErrorSeverityLow      ErrorSeverity = "low"
	ErrorSeverityMedium   ErrorSeverity = "medium"
	ErrorSeverityHigh     ErrorSeverity = "high"
	ErrorSeverityCritical ErrorSeverity = "critical"
)

type Severity

type Severity string

Severity represents the severity level of an error

const (
	SeverityLow      Severity = "LOW"
	SeverityMedium   Severity = "MEDIUM"
	SeverityHigh     Severity = "HIGH"
	SeverityCritical Severity = "CRITICAL"
)

func GetSeverity

func GetSeverity(err error) Severity

GetSeverity returns the severity of an error

Jump to

Keyboard shortcuts

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