errors

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package errors provides a structured error taxonomy for swarm coordination in agentkit. It defines a comprehensive set of error types, codes, and categories that enable consistent error handling across distributed agent systems.

Error Categories

Errors are classified into four categories:

  • Transient: Temporary failures where retry may succeed (network issues, etc.)
  • Permanent: Failures where retry will not help (invalid input, not found, etc.)
  • Resource: Resource exhaustion issues (rate limits, quotas, etc.)
  • Internal: Unexpected errors indicating bugs or system failures

Error Codes

Each error has a specific code that identifies the type of failure:

  • TIMEOUT: Operation timed out
  • RATE_LIMITED: Rate limit exceeded
  • NOT_FOUND: Resource not found
  • CONFLICT: Conflicting operation
  • UNAUTHORIZED: Authentication/authorization failure
  • And more...

Usage

Create a new error:

err := errors.New(errors.ErrCodeTimeout, "operation timed out")

Wrap an existing error with context:

wrapped := errors.Wrap(err, "fetching agent state")

Check if an error is retryable:

if agentErr, ok := errors.AsAgentError(err); ok && agentErr.Retryable() {
    // retry logic
}

JSON Serialization

All errors support JSON serialization for cross-agent communication:

data, err := json.Marshal(agentErr)

Errors can be deserialized back:

var agentErr errors.Error
json.Unmarshal(data, &agentErr)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllRetryable

func AllRetryable(errs []error) bool

AllRetryable checks if all errors in the slice are retryable. Returns true for empty slice.

func AnyRetryable

func AnyRetryable(errs []error) bool

AnyRetryable checks if any error in the slice is retryable. Returns false for empty slice.

func Cause

func Cause(err error) error

Cause returns the root cause of the error chain.

func Collect

func Collect(errs ...error) []error

Collect gathers multiple errors into a slice, filtering nils.

func FirstRetryable

func FirstRetryable(errs []error) error

FirstRetryable returns the first retryable error from a slice. Returns nil if no retryable error is found.

func GetMetadata

func GetMetadata(err error) map[string]string

GetMetadata extracts metadata from an error. Returns nil if err is not an AgentError.

func Is

func Is(err error, code ErrorCode) bool

Is checks if any error in the chain has the given error code.

func IsCategory

func IsCategory(err error, category ErrorCategory) bool

IsCategory checks if any error in the chain has the given category.

func IsInternal

func IsInternal(err error) bool

IsInternal checks if the error is an internal error.

func IsPermanent

func IsPermanent(err error) bool

IsPermanent checks if the error is permanent.

func IsResource

func IsResource(err error) bool

IsResource checks if the error is resource-related.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable checks if the error is retryable.

func IsTransient

func IsTransient(err error) bool

IsTransient checks if the error is transient.

func Join

func Join(errs ...error) error

Join combines multiple errors into a single error. If all errors are nil, returns nil. Uses errors.Join from the standard library.

Types

type AgentError

type AgentError interface {
	error

	// Code returns the specific error code identifying the failure type.
	Code() ErrorCode

	// Category returns the error category for retry/handling decisions.
	Category() ErrorCategory

	// Retryable returns true if the operation may succeed on retry.
	Retryable() bool

	// Metadata returns additional context as key-value pairs.
	Metadata() map[string]string

	// Unwrap returns the underlying error, if any.
	Unwrap() error
}

AgentError is the interface for all structured errors in agentkit. It extends the standard error interface with additional context for swarm coordination and retry logic.

func AsAgentError

func AsAgentError(err error) AgentError

As attempts to extract an AgentError from an error chain. Returns nil if no AgentError is found.

type Error

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

Error is the concrete implementation of AgentError.

func AgentOffline

func AgentOffline(agentID string, opts ...Option) *Error

AgentOffline creates an agent offline error.

func Conflict

func Conflict(message string, opts ...Option) *Error

Conflict creates a conflict error.

func CoordinationFailure

func CoordinationFailure(message string, opts ...Option) *Error

CoordinationFailure creates a coordination failure error.

func Forbidden

func Forbidden(message string, opts ...Option) *Error

Forbidden creates a forbidden error.

func FromCode

func FromCode(code ErrorCode, opts ...Option) *Error

FromCode creates an error with the default description for the code.

func Internal

func Internal(message string, opts ...Option) *Error

Internal creates an internal error.

func InvalidInput

func InvalidInput(message string, opts ...Option) *Error

InvalidInput creates an invalid input error.

func New

func New(code ErrorCode, message string, opts ...Option) *Error

New creates a new Error with the given code and message.

func Newf

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

Newf creates a new Error with a formatted message.

func NotFound

func NotFound(message string, opts ...Option) *Error

NotFound creates a not found error.

func RateLimited

func RateLimited(message string, opts ...Option) *Error

RateLimited creates a rate limit error.

func RecoverPanic

func RecoverPanic(recovered interface{}) *Error

RecoverPanic converts a recovered panic value into an Error.

func TaskFailed

func TaskFailed(taskID, reason string, opts ...Option) *Error

TaskFailed creates a task failed error.

func Timeout

func Timeout(message string, opts ...Option) *Error

Timeout creates a timeout error.

func Unauthorized

func Unauthorized(message string, opts ...Option) *Error

Unauthorized creates an unauthorized error.

func Wrap

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

Wrap wraps an error with additional context while preserving the error chain. If err is nil, Wrap returns nil. If err is already an AgentError, it wraps it with the new message. Otherwise, it creates a new Internal error wrapping the original.

func WrapWithCode

func WrapWithCode(err error, code ErrorCode, message string, opts ...Option) *Error

WrapWithCode wraps an error with a specific error code.

func Wrapf

func Wrapf(err error, format string, args ...interface{}) *Error

Wrapf wraps an error with a formatted message.

func (*Error) AgentID

func (e *Error) AgentID() string

AgentID returns the source agent ID, if set.

func (*Error) Category

func (e *Error) Category() ErrorCategory

Category returns the error category.

func (*Error) Code

func (e *Error) Code() ErrorCode

Code returns the error code.

func (*Error) Error

func (e *Error) Error() string

Error returns the error message.

func (*Error) MarshalJSON

func (e *Error) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Error) Metadata

func (e *Error) Metadata() map[string]string

Metadata returns the error metadata.

func (*Error) Retryable

func (e *Error) Retryable() bool

Retryable returns whether this error is retryable.

func (*Error) TaskID

func (e *Error) TaskID() string

TaskID returns the related task ID, if set.

func (*Error) Timestamp

func (e *Error) Timestamp() time.Time

Timestamp returns when the error occurred.

func (*Error) UnmarshalJSON

func (e *Error) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause.

type ErrorCategory

type ErrorCategory string

ErrorCategory classifies errors by their nature and retry semantics.

const (
	// CategoryTransient indicates temporary failures where retry may succeed.
	// Examples: network timeouts, temporary service unavailability.
	CategoryTransient ErrorCategory = "transient"

	// CategoryPermanent indicates failures where retry will not help.
	// Examples: invalid input, resource not found, permission denied.
	CategoryPermanent ErrorCategory = "permanent"

	// CategoryResource indicates resource exhaustion or quota issues.
	// Examples: rate limiting, storage quota exceeded, connection pool exhausted.
	CategoryResource ErrorCategory = "resource"

	// CategoryInternal indicates unexpected errors, bugs, or system failures.
	// Examples: nil pointer, assertion failures, corrupted state.
	CategoryInternal ErrorCategory = "internal"
)

Error categories define how errors should be handled.

func Category

func Category(err error) ErrorCategory

Category extracts the error category from an error, if available. Returns empty string if err is not an AgentError.

func (ErrorCategory) IsRetryable

func (c ErrorCategory) IsRetryable() bool

IsRetryable returns true if errors in this category may succeed on retry.

func (ErrorCategory) String

func (c ErrorCategory) String() string

String returns the string representation of the category.

type ErrorCode

type ErrorCode string

ErrorCode identifies specific error types within categories.

const (
	// Transient errors
	ErrCodeTimeout     ErrorCode = "TIMEOUT"     // Operation timed out
	ErrCodeUnavailable ErrorCode = "UNAVAILABLE" // Service temporarily unavailable
	ErrCodeNetworkErr  ErrorCode = "NETWORK_ERR" // Network connectivity issue
	ErrCodeRetryLater  ErrorCode = "RETRY_LATER" // Server requested retry

	// Permanent errors
	ErrCodeNotFound      ErrorCode = "NOT_FOUND"      // Resource does not exist
	ErrCodeConflict      ErrorCode = "CONFLICT"       // Conflicting operation or state
	ErrCodeInvalidInput  ErrorCode = "INVALID_INPUT"  // Malformed or invalid input
	ErrCodeUnauthorized  ErrorCode = "UNAUTHORIZED"   // Authentication failed
	ErrCodeForbidden     ErrorCode = "FORBIDDEN"      // Authorization denied
	ErrCodeAlreadyExists ErrorCode = "ALREADY_EXISTS" // Resource already exists
	ErrCodePrecondition  ErrorCode = "PRECONDITION"   // Precondition not met
	ErrCodeUnsupported   ErrorCode = "UNSUPPORTED"    // Operation not supported
	ErrCodeCanceled      ErrorCode = "CANCELED"       // Operation was canceled

	// Resource errors
	ErrCodeRateLimit     ErrorCode = "RATE_LIMITED"   // Rate limit exceeded
	ErrCodeQuotaExceeded ErrorCode = "QUOTA_EXCEEDED" // Resource quota exhausted
	ErrCodeResourceBusy  ErrorCode = "RESOURCE_BUSY"  // Resource is busy/locked
	ErrCodeCapacity      ErrorCode = "CAPACITY"       // System at capacity

	// Internal errors
	ErrCodeInternal   ErrorCode = "INTERNAL"   // Unexpected internal error
	ErrCodeCorruption ErrorCode = "CORRUPTION" // Data corruption detected
	ErrCodeAssertion  ErrorCode = "ASSERTION"  // Assertion/invariant violation
	ErrCodePanic      ErrorCode = "PANIC"      // Recovered from panic

	// Agent-specific errors
	ErrCodeAgentOffline      ErrorCode = "AGENT_OFFLINE"      // Target agent is offline
	ErrCodeAgentBusy         ErrorCode = "AGENT_BUSY"         // Agent is processing another task
	ErrCodeTaskFailed        ErrorCode = "TASK_FAILED"        // Task execution failed
	ErrCodeCoordination      ErrorCode = "COORDINATION"       // Swarm coordination failure
	ErrCodeHandoffFailed     ErrorCode = "HANDOFF_FAILED"     // Agent handoff failed
	ErrCodeCapabilityMissing ErrorCode = "CAPABILITY_MISSING" // Required capability not available
)

Error codes for common failure scenarios.

func Code

func Code(err error) ErrorCode

Code extracts the error code from an error, if available. Returns empty string if err is not an AgentError.

func (ErrorCode) DefaultCategory

func (c ErrorCode) DefaultCategory() ErrorCategory

DefaultCategory returns the default category for an error code.

func (ErrorCode) DefaultRetryable

func (c ErrorCode) DefaultRetryable() bool

DefaultRetryable returns whether this error code is typically retryable.

func (ErrorCode) Description

func (c ErrorCode) Description() string

Description returns a human-readable description for the error code.

func (ErrorCode) String

func (c ErrorCode) String() string

String returns the string representation of the error code.

type Option

type Option func(*Error)

Option is a functional option for configuring an Error.

func WithAgentID

func WithAgentID(id string) Option

WithAgentID sets the source agent ID.

func WithCategory

func WithCategory(cat ErrorCategory) Option

WithCategory overrides the default category.

func WithCause

func WithCause(cause error) Option

WithCause sets the underlying cause.

func WithMetadata

func WithMetadata(key, value string) Option

WithMetadata adds metadata key-value pairs.

func WithMetadataMap

func WithMetadataMap(m map[string]string) Option

WithMetadataMap adds multiple metadata key-value pairs.

func WithRetryable

func WithRetryable(retryable bool) Option

WithRetryable explicitly sets whether the error is retryable.

func WithTaskID

func WithTaskID(id string) Option

WithTaskID sets the related task ID.

func WithTimestamp

func WithTimestamp(t time.Time) Option

WithTimestamp sets a custom timestamp.

Jump to

Keyboard shortcuts

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