Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

README.md

errors

Package errors provides custom error types and utilities for consistent error handling throughout the Starmap application.

errors

import "github.com/agentstation/starmap/pkg/errors"

Package errors provides custom error types for the starmap system. These errors enable better error handling, programmatic error checking, and improved debugging throughout the application.

Example

Example demonstrates basic error creation and checking.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/errors"
)

func main() {
	// Create a not found error
	err := &errors.NotFoundError{
		Resource: "model",
		ID:       "gpt-5",
	}

	// Check error type
	if errors.IsNotFound(err) {
		fmt.Println("Resource not found")
	}

}

Output

Resource not found

Example (API Error)

Example_aPIError demonstrates API error handling.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/errors"
)

func main() {
	// Simulate an API error
	err := &errors.APIError{
		Provider:   "openai",
		Endpoint:   "https://api.openai.com/v1/models",
		StatusCode: 429,
		Message:    "Rate limit exceeded",
	}

	// Check and handle specific error types
	switch err.StatusCode {
	case 429:
		fmt.Println("Rate limited - retry later")
	case 401:
		fmt.Println("Authentication failed")
	case 500:
		fmt.Println("Server error")
	}

}

Output

Rate limited - retry later

Example (Authentication Error)

Example_authenticationError shows authentication error handling.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/errors"
)

func main() {
	// Create authentication error
	err := &errors.AuthenticationError{
		Provider: "anthropic",
		Message:  "API key not configured",
	}

	// Auth error is already typed
	fmt.Printf("Auth failed for %s: %s\n",
		err.Provider, err.Message)

}

Output

Auth failed for anthropic: API key not configured

Example (Error Chaining)

Example_errorChaining shows chained error handling.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/errors"
)

func main() {
	// Create a chain of errors
	baseErr := &errors.NotFoundError{
		Resource: "file",
		ID:       "config.json",
	}

	parseErr := &errors.ParseError{
		Format:  "json",
		File:    "config.json",
		Message: "Failed to parse config",
		Err:     baseErr,
	}

	// Check through the chain using standard library
	if parseErr.Err != nil {
		if _, ok := parseErr.Err.(*errors.NotFoundError); ok {
			fmt.Println("File not found in parse chain")
		}
	}

}

Output

File not found in parse chain

Example (Error Recovery)

Example_errorRecovery demonstrates error recovery strategies.

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/agentstation/starmap/pkg/errors"
)

func main() {
	// Retry strategy for rate limits
	var attemptRequest func() error
	attemptRequest = func() error {
		// Simulate API call
		return &errors.APIError{
			Provider:   "openai",
			StatusCode: 429,
			Message:    "Rate limit: 3 per second",
		}
	}

	maxRetries := 3
	for i := 0; i < maxRetries; i++ {
		err := attemptRequest()

		if apiErr, ok := err.(*errors.APIError); ok && apiErr.StatusCode == 429 {
			fmt.Printf("Attempt %d: Rate limited, retrying...\n", i+1)
			time.Sleep(time.Second) // Simple backoff
			continue
		}

		if err != nil {
			log.Fatal(err)
		}

		break
	}
}

Example (Error Wrapping)

Example_errorWrapping demonstrates error wrapping patterns.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/errors"
)

func main() {
	// Original error
	originalErr := fmt.Errorf("connection refused")

	// Wrap with IO error
	ioErr := errors.WrapIO("connect", "api.openai.com", originalErr)

	// Wrap with API error
	_ = &errors.APIError{
		Provider:   "openai",
		Endpoint:   "https://api.openai.com/v1/models",
		StatusCode: 0,
		Message:    "Failed to connect",
		Err:        ioErr,
	}

	// API error type is already known
	fmt.Println("API error occurred")

}

Output

API error occurred

Example (HTTP Status Mapping)

Example_hTTPStatusMapping maps HTTP codes to error types.

package main

import (
	"fmt"
	"net/http"

	"github.com/agentstation/starmap/pkg/errors"
)

func main() {
	// Map HTTP status to appropriate error
	mapHTTPError := func(status int, provider string) error {
		switch status {
		case http.StatusNotFound:
			return &errors.NotFoundError{
				Resource: "endpoint",
				ID:       provider,
			}
		case http.StatusUnauthorized:
			return &errors.AuthenticationError{
				Provider: provider,
				Message:  "Invalid credentials",
			}
		case http.StatusTooManyRequests:
			return &errors.APIError{
				Provider:   provider,
				StatusCode: 429,
				Message:    "Rate limit exceeded",
			}
		default:
			return &errors.APIError{
				Provider:   provider,
				StatusCode: status,
				Message:    http.StatusText(status),
			}
		}
	}

	err := mapHTTPError(401, "openai")
	if _, ok := err.(*errors.AuthenticationError); ok {
		fmt.Println("Authentication required")
	}

}

Output

Authentication required

Example (Process Error)

Example_processError demonstrates subprocess error handling.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/errors"
)

func main() {
	// Create process error
	err := &errors.ProcessError{
		Operation: "git clone",
		Command:   "git clone https://github.com/repo.git",
		Output:    "fatal: repository not found",
		ExitCode:  128,
	}

	// Handle process errors
	fmt.Printf("Command failed with exit code %d\n", err.ExitCode)
	if err.ExitCode == 128 {
		fmt.Println("Git configuration error")
	}

}

Output

Command failed with exit code 128
Git configuration error

Example (Rate Limit Error)

Example_rateLimitError demonstrates rate limit handling with retry.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/errors"
)

func main() {
	// Create API error for rate limiting
	err := &errors.APIError{
		Provider:   "openai",
		StatusCode: 429,
		Message:    "Rate limit exceeded. Try again in 30 seconds.",
	}

	// Handle rate limit
	if err.StatusCode == 429 {
		fmt.Printf("Rate limited: %s\n", err.Message)
	}

}

Output

Rate limited: Rate limit exceeded. Try again in 30 seconds.

Example (Validation Error)

Example_validationError shows input validation errors.

package main

import (
	"fmt"

	"github.com/agentstation/starmap/pkg/errors"
)

func main() {
	// Validate input
	apiKey := ""
	if apiKey == "" {
		err := &errors.ValidationError{
			Field:   "api_key",
			Value:   apiKey,
			Message: "API key cannot be empty",
		}
		fmt.Println(err.Error())
	}

}

Output

validation failed for field api_key: API key cannot be empty

Index

Variables

Common sentinel errors for the starmap system.

var (
    // ErrNotFound indicates that a requested resource was not found.
    ErrNotFound = errors.New("not found")

    // ErrAlreadyExists indicates that a resource already exists.
    ErrAlreadyExists = errors.New("already exists")

    // ErrInvalidInput indicates that provided input was invalid.
    ErrInvalidInput = errors.New("invalid input")

    // ErrAPIKeyRequired indicates that an API key is required but not provided.
    ErrAPIKeyRequired = errors.New("API key required")

    // ErrAPIKeyInvalid indicates that the provided API key is invalid.
    ErrAPIKeyInvalid = errors.New("API key invalid")

    // ErrProviderUnavailable indicates that a provider is temporarily unavailable.
    ErrProviderUnavailable = errors.New("provider unavailable")

    // ErrRateLimited indicates that the API rate limit has been exceeded.
    ErrRateLimited = errors.New("rate limited")

    // ErrTimeout indicates that an operation timed out.
    ErrTimeout = errors.New("operation timed out")

    // ErrCanceled indicates that an operation was canceled.
    ErrCanceled = errors.New("operation canceled")

    // ErrNotImplemented indicates that a feature is not yet implemented.
    ErrNotImplemented = errors.New("not implemented")

    // ErrReadOnly indicates an attempt to modify a read-only resource.
    ErrReadOnly = errors.New("read only")
)

New returns an error that formats as the given text. It's an alias for the standard library errors.New for convenience.

var New = errors.New

func IsAPIKeyError(err error) bool

IsAPIKeyError checks if an error is related to API keys.

func IsAlreadyExists(err error) bool

IsAlreadyExists checks if an error is an already exists error.

func IsCanceled(err error) bool

IsCanceled checks if an error is a cancellation error.

func IsNotFound(err error) bool

IsNotFound checks if an error is a not found error.

func IsProviderUnavailable(err error) bool

IsProviderUnavailable checks if an error indicates provider unavailability.

func IsRateLimited(err error) bool

IsRateLimited checks if an error is a rate limit error.

func IsTimeout(err error) bool

IsTimeout checks if an error is a timeout error.

func IsValidationError(err error) bool

IsValidationError checks if an error is a validation error.

func WrapAPI

func WrapAPI(provider string, statusCode int, err error) error

WrapAPI wraps an error as an APIError.

func WrapIO

func WrapIO(operation, path string, err error) error

WrapIO wraps an error as an IOError.

func WrapParse(format, file string, err error) error

WrapParse wraps an error as a ParseError.

func WrapResource(operation, resource, id string, err error) error

WrapResource wraps an error as a ResourceError.

func WrapValidation(field string, err error) error

WrapValidation wraps an error as a ValidationError.

APIError represents an error from a provider API.

type APIError struct {
    Provider   string // Provider ID as string
    StatusCode int
    Message    string
    Endpoint   string
    Err        error
}

func NewAPIError(provider string, statusCode int, message string) *APIError

NewAPIError creates a new APIError.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) Is

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

Is implements errors.Is support.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap implements errors.Unwrap.

AuthenticationError represents an authentication/authorization error.

type AuthenticationError struct {
    Provider string
    Method   string // "api_key", "oauth", "basic", etc.
    Message  string
    Err      error
}

func NewAuthenticationError(provider, method, message string, err error) *AuthenticationError

NewAuthenticationError creates a new AuthenticationError.

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

Error implements the error interface.

func (*AuthenticationError) Is

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

Is implements errors.Is support.

func (*AuthenticationError) Unwrap

func (e *AuthenticationError) Unwrap() error

Unwrap implements errors.Unwrap.

ConfigError represents a configuration error.

type ConfigError struct {
    Component string
    Message   string
    Err       error
}

func NewConfigError(component, message string, err error) *ConfigError

NewConfigError creates a new ConfigError.

func (*ConfigError) Error

func (e *ConfigError) Error() string

Error implements the error interface.

func (*ConfigError) Unwrap

func (e *ConfigError) Unwrap() error

Unwrap implements errors.Unwrap.

DependencyError indicates a required external dependency is missing.

type DependencyError struct {
    Dependency string
    Message    string
}

func (*DependencyError) Error

func (e *DependencyError) Error() string

Error implements the error interface.

type IOError

IOError represents an error during I/O operations.

type IOError struct {
    Operation string // "read", "write", "create", "delete", "open", "close"
    Path      string
    Message   string
    Err       error
}

func NewIOError(operation, path string, err error) *IOError

NewIOError creates a new IOError.

func (*IOError) Error

func (e *IOError) Error() string

Error implements the error interface.

func (*IOError) Unwrap

func (e *IOError) Unwrap() error

Unwrap implements errors.Unwrap.

MergeError represents an error during catalog merge operations.

type MergeError struct {
    Source      string
    Target      string
    ConflictIDs []string
    Err         error
}

func NewMergeError(source, target string, conflictIDs []string, err error) *MergeError

NewMergeError creates a new MergeError.

func (*MergeError) Error

func (e *MergeError) Error() string

Error implements the error interface.

func (*MergeError) Unwrap

func (e *MergeError) Unwrap() error

Unwrap implements errors.Unwrap.

NotFoundError represents an error when a resource is not found.

type NotFoundError struct {
    Resource string
    ID       string
}

func NewNotFoundError(resource, id string) *NotFoundError

NewNotFoundError creates a new NotFoundError.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

Error implements the error interface.

func (*NotFoundError) Is

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

Is implements errors.Is support.

ParseError represents an error when parsing data formats.

type ParseError struct {
    Format  string // "json", "yaml", "toml", etc.
    File    string
    Line    int
    Column  int
    Message string
    Err     error
}

func NewParseError(format, file string, message string, err error) *ParseError

NewParseError creates a new ParseError.

func (*ParseError) Error

func (e *ParseError) Error() string

Error implements the error interface.

func (*ParseError) Unwrap

func (e *ParseError) Unwrap() error

Unwrap implements errors.Unwrap.

ProcessError represents an error from an external process or command.

type ProcessError struct {
    Operation string // What operation was being performed
    Command   string // The command that was executed
    Output    string // Stdout/stderr output from the process
    ExitCode  int    // Exit code if available
    Err       error  // Underlying error
}

func NewProcessError(operation, command, output string, err error) *ProcessError

NewProcessError creates a new ProcessError.

func (*ProcessError) Error

func (e *ProcessError) Error() string

Error implements the error interface.

func (*ProcessError) Unwrap

func (e *ProcessError) Unwrap() error

Unwrap implements errors.Unwrap.

ResourceError represents an error during resource operations.

type ResourceError struct {
    Operation string // "create", "update", "delete", "fetch"
    Resource  string // "catalog", "provider", "model", "author"
    ID        string
    Message   string
    Err       error
}

func NewResourceError(operation, resource, id string, err error) *ResourceError

NewResourceError creates a new ResourceError.

func (*ResourceError) Error

func (e *ResourceError) Error() string

Error implements the error interface.

func (*ResourceError) Unwrap

func (e *ResourceError) Unwrap() error

Unwrap implements errors.Unwrap.

SyncError represents an error during sync operations.

type SyncError struct {
    Provider string
    Models   []string
    Err      error
}

func NewSyncError(provider string, models []string, err error) *SyncError

NewSyncError creates a new SyncError.

func (*SyncError) Error

func (e *SyncError) Error() string

Error implements the error interface.

func (*SyncError) Unwrap

func (e *SyncError) Unwrap() error

Unwrap implements errors.Unwrap.

TimeoutError represents an operation timeout.

type TimeoutError struct {
    Operation string
    Duration  string
    Message   string
}

func NewTimeoutError(operation, duration, message string) *TimeoutError

NewTimeoutError creates a new TimeoutError.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error implements the error interface.

func (*TimeoutError) Is

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

Is implements errors.Is support.

ValidationError represents a validation failure.

type ValidationError struct {
    Field   string
    Value   any
    Message string
}

func NewValidationError(field string, value any, message string) *ValidationError

NewValidationError creates a new ValidationError.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

func (*ValidationError) Is

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

Is implements errors.Is support.

Generated by gomarkdoc