errors

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAgentNotFound       = errors.New("agent not found")
	ErrAgentTimeout        = errors.New("agent execution timeout")
	ErrAgentPanic          = errors.New("agent internal panic")
	ErrTaskQueueFull       = errors.New("task queue is full")
	ErrDependencyCycle     = errors.New("task dependency cycle detected")
	ErrAgentNotReady       = errors.New("agent not ready")
	ErrAgentBusy           = errors.New("agent is busy")
	ErrAgentAlreadyStarted = errors.New("agent already started")
	ErrAgentNotRunning     = errors.New("agent not running")
	ErrQueueNotInitialized = errors.New("message queue not initialized")
	ErrToolNotFound        = errors.New("tool not found")
	ErrMaxStepsExceeded    = errors.New("agent max steps exceeded")
)

Sentinel errors for Agent module.

View Source
var (
	ErrInvalidMessage  = errors.New("invalid message format")
	ErrMessageTimeout  = errors.New("message send timeout")
	ErrHeartbeatMissed = errors.New("heartbeat missed")
	ErrQueueFull       = errors.New("message queue is full")
	ErrQueueEmpty      = errors.New("message queue is empty")
	ErrQueueClosed     = errors.New("message queue is closed")
)

Sentinel errors for Protocol module.

View Source
var (
	ErrDBConnectionFailed = errors.New("database connection failed")
	ErrQueryFailed        = errors.New("query execution failed")
	ErrVectorSearchFailed = errors.New("vector search failed")
	ErrRecordNotFound     = errors.New("record not found")
	ErrTransactionFailed  = errors.New("transaction failed")
	ErrNoTransaction      = errors.New("no active transaction")
	ErrInvalidArgument    = errors.New("invalid argument provided")
	ErrCircuitBreakerOpen = errors.New("circuit breaker is open")
	ErrServiceUnavailable = errors.New("service is temporarily unavailable")
	ErrInvalidState       = errors.New("invalid state")
	ErrSecretExpired      = errors.New("secret has expired")
	ErrNotImplemented     = errors.New("feature not implemented yet")
	ErrBufferFull         = errors.New("write buffer is full")
)

Sentinel errors for Storage module.

View Source
var (
	ErrLLMRequestFailed    = errors.New("LLM request failed")
	ErrLLMTimeout          = errors.New("LLM response timeout")
	ErrLLMQuotaExceeded    = errors.New("LLM quota exceeded")
	ErrLLMInvalidResponse  = errors.New("LLM invalid response")
	ErrLLMParserFailed     = errors.New("LLM output parsing failed")
	ErrLLMValidationFailed = errors.New("LLM output validation failed")
)

Sentinel errors for LLM module.

View Source
var (
	ErrRateLimitExceeded = errors.New("rate limit exceeded")
	ErrDBTimeout         = errors.New("database operation timeout")
)

Sentinel errors for Rate Limiting module.

View Source
var (
	ErrInvalidUserID = errors.New("invalid user ID")
	ErrInvalidAge    = errors.New("invalid age")
	ErrInvalidBudget = errors.New("invalid budget range")
	ErrInvalidInput  = errors.New("invalid input parameter")
	ErrNilPointer    = errors.New("nil pointer error")
)

Sentinel errors for Parameter validation.

View Source
var (
	ErrProfileParsingFailed        = errors.New("profile parsing failed")
	ErrProfileValidationFailed     = errors.New("profile validation failed")
	ErrMaxRetriesExceeded          = errors.New("max retries exceeded")
	ErrTaskExecutionFailed         = errors.New("task execution failed")
	ErrPromptRenderFailed          = errors.New("prompt render failed")
	ErrLLMGenerateFailed           = errors.New("LLM generate failed")
	ErrTaskPlannerNotInitialized   = errors.New("task planner not initialized")
	ErrProfileParserNotInitialized = errors.New("profile parser not initialized")
	ErrDispatchNotInitialized      = errors.New("task dispatcher not initialized")
	ErrResultAggNotInitialized     = errors.New("result aggregator not initialized")
	ErrDispatchFailed              = errors.New("task dispatch failed")
)

Sentinel errors for parsing and retry.

View Source
var (
	ErrWorkflowNotFound     = errors.New("workflow not found")
	ErrWorkflowLoadFailed   = errors.New("workflow load failed")
	ErrWorkflowCyclicDAG    = errors.New("workflow has cyclic dependency")
	ErrWorkflowInvalidPhase = errors.New("invalid workflow phase")
)

Sentinel errors for Workflow module.

View Source
var (
	ErrBackpressureTriggered = errors.New("backpressure triggered")
	ErrTokenBucketExhausted  = errors.New("token bucket exhausted")
)

Sentinel errors for Rate Limiter.

View Source
var DefaultErrorStrategiesConfig = ConfigFile{
	Version: "1.0",
	Strategies: map[string]ErrorStrategy{

		"01-002": {Backoff: 5 * time.Second, MaxRetries: 3, DLQEnabled: true, AlertEnabled: false},
		"01-003": {Backoff: 10 * time.Second, MaxRetries: 2, DLQEnabled: true, AlertEnabled: true, AlertMessage: "Agent panic detected"},
		"01-004": {Backoff: 1 * time.Second, MaxRetries: 5, DLQEnabled: false, AlertEnabled: true, AlertMessage: "Task queue full"},

		"02-002": {Backoff: 3 * time.Second, MaxRetries: 3, DLQEnabled: false, AlertEnabled: false},
		"02-003": {Backoff: 5 * time.Second, MaxRetries: 5, DLQEnabled: true, AlertEnabled: true, AlertMessage: "Heartbeat missed"},

		"03-001": {Backoff: 2 * time.Second, MaxRetries: 3, DLQEnabled: false, AlertEnabled: true, AlertMessage: "DB connection failed"},
		"03-002": {Backoff: 1 * time.Second, MaxRetries: 2, DLQEnabled: false, AlertEnabled: false},
		"03-003": {Backoff: 2 * time.Second, MaxRetries: 2, DLQEnabled: false, AlertEnabled: false},

		"04-001": {Backoff: 3 * time.Second, MaxRetries: 3, DLQEnabled: false, AlertEnabled: true, AlertMessage: "LLM request failed"},
		"04-002": {Backoff: 5 * time.Second, MaxRetries: 2, DLQEnabled: false, AlertEnabled: false},
		"04-003": {Backoff: 0, MaxRetries: 0, DLQEnabled: false, AlertEnabled: true, AlertMessage: "LLM quota exceeded"},
		"04-005": {Backoff: 1 * time.Second, MaxRetries: 3, DLQEnabled: false, AlertEnabled: false},
		"04-006": {Backoff: 0, MaxRetries: 0, DLQEnabled: false, AlertEnabled: true, AlertMessage: "LLM validation failed"},
		"04-007": {Backoff: 0, MaxRetries: 0, DLQEnabled: false, AlertEnabled: true, AlertMessage: "LLM authentication failed (401) - check API key"},
	},
}

DefaultErrorStrategiesConfig provides the default error strategies as a config file.

View Source
var DefaultStrategy = ErrorStrategy{
	Backoff:      1 * time.Second,
	MaxRetries:   1,
	DLQEnabled:   false,
	AlertEnabled: false,
}

DefaultStrategy is the fallback strategy when no specific strategy is found.

View Source
var ModelValidationErrors = map[string]error{
	"ErrInvalidUserID": ErrInvalidUserID,
	"ErrInvalidAge":    ErrInvalidAge,
	"ErrInvalidBudget": ErrInvalidBudget,
	"ErrInvalidInput":  ErrInvalidInput,
	"ErrNilPointer":    ErrNilPointer,
}

ModelValidationErrors returns validation errors for models package.

Functions

func ExportStrategiesToConfig

func ExportStrategiesToConfig(configPath string) error

ExportStrategiesToConfig exports current strategies to a configuration file.

func FormatError

func FormatError(err error) string

FormatError formats an error for logging or display.

func GetAlertMessage

func GetAlertMessage(code string) string

GetAlertMessage returns the alert message for the error code. Uses the configurable strategy registry.

func GetAllStrategies

func GetAllStrategies() map[string]ErrorStrategy

GetAllStrategies returns a copy of all strategies.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable checks if an error is retryable.

func LoadStrategiesFromConfig

func LoadStrategiesFromConfig(configPath string) error

LoadStrategiesFromConfig loads error strategies from a configuration file. Supported formats: JSON

func SetAllowedDir

func SetAllowedDir(dir string)

SetAllowedDir sets the allowed directory for config file loading. This is a security measure to prevent path traversal attacks.

func SetStrategy

func SetStrategy(code string, strategy ErrorStrategy) error

SetStrategy sets or updates an error strategy for a specific error code.

Args: code - error code identifier. strategy - error strategy configuration. Returns error if strategy validation fails.

func ShouldAlert

func ShouldAlert(code string) bool

ShouldAlert checks if the error should trigger an alert. Uses the configurable strategy registry.

func ShouldDLQ

func ShouldDLQ(code string) bool

ShouldDLQ checks if the error should be sent to DLQ. Uses the configurable strategy registry.

Types

type AlertFunc

type AlertFunc func(ctx context.Context, message string)

AlertFunc defines the function to send alert.

type AppError

type AppError struct {
	Code    *ErrorCode
	Err     error
	Context map[string]any
}

AppError represents an application error with context.

func New

func New(code *ErrorCode) *AppError

New creates a new AppError.

func Wrap

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

Wrap wraps an error with the error code.

func (*AppError) Error

func (e *AppError) Error() string

Error returns the error message.

func (*AppError) IsRetryable

func (e *AppError) IsRetryable() bool

IsRetryable checks if the error is retryable.

func (*AppError) ShouldRetry

func (e *AppError) ShouldRetry(attempt int) bool

ShouldRetry checks if the error should be retried based on attempt count.

func (*AppError) Unwrap

func (e *AppError) Unwrap() error

Unwrap returns the underlying error.

func (*AppError) WithContext

func (e *AppError) WithContext(key string, value any) *AppError

WithContext adds context to the error.

type ConfigFile

type ConfigFile struct {
	Version    string                   `json:"version"`
	Strategies map[string]ErrorStrategy `json:"strategies"`
}

ConfigFile defines the structure for error strategy configuration file.

type DLQFunc

type DLQFunc func(ctx context.Context, msg *DLQMessage) error

DLQFunc defines the function to send error to DLQ.

type DLQMessage

type DLQMessage struct {
	ErrorCode  string
	Error      error
	Context    map[string]any
	Timestamp  time.Time
	RetryCount int
}

DLQMessage represents a message for dead letter queue.

type ErrorCode

type ErrorCode struct {
	Code       string        `json:"code"`
	Message    string        `json:"message"`
	Module     string        `json:"module"`
	Retry      bool          `json:"retry"`
	RetryMax   int           `json:"retry_max"`
	Backoff    time.Duration `json:"backoff"`
	HTTPStatus int           `json:"http_status"`
}

ErrorCode represents a structured error code.

func NewErrorCode

func NewErrorCode(code, message, module string, retry bool, retryMax int, backoff time.Duration, httpStatus int) *ErrorCode

NewErrorCode creates a new ErrorCode.

type ErrorStrategy

type ErrorStrategy struct {
	Backoff      time.Duration
	MaxRetries   int
	DLQEnabled   bool
	AlertEnabled bool
	AlertMessage string
}

ErrorStrategy defines retry and handling strategy for error codes.

Example configuration:

{
  "code": "01-002",
  "backoff": "5s",
  "maxRetries": 3,
  "dlqEnabled": true,
  "alertEnabled": false,
  "alertMessage": ""
}

Fields:

  • Backoff: Wait duration before retry
  • MaxRetries: Maximum number of retry attempts (0 = no retry)
  • DLQEnabled: Send to Dead Letter Queue on final failure
  • AlertEnabled: Trigger alert notification
  • AlertMessage: Custom alert message (optional)

func GetStrategy

func GetStrategy(code string) ErrorStrategy

GetStrategy returns the error strategy for the given error code. Returns default strategy if code not found.

type Handler

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

Handler handles errors with retry and DLQ logic.

func NewHandler

func NewHandler(dlq DLQFunc, alertFunc AlertFunc) *Handler

NewHandler creates a new error handler.

func (*Handler) HandleError

func (h *Handler) HandleError(ctx context.Context, appErr *AppError, retryCount int)

HandleError handles an error with retry logic.

func (*Handler) RetryWithBackoff

func (h *Handler) RetryWithBackoff(ctx context.Context, appErr *AppError, attempt int, fn func() error) error

RetryWithBackoff performs retry with exponential backoff.

type InvalidStrategyError

type InvalidStrategyError struct {
	Field   string
	Message string
}

InvalidStrategyError is returned when an error strategy configuration is invalid.

func (*InvalidStrategyError) Error

func (e *InvalidStrategyError) Error() string

Jump to

Keyboard shortcuts

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