errors

package
v0.0.0-...-9218f0a Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2025 License: MIT Imports: 7 Imported by: 0

README

Error Handling Package

Overview

The errors package provides a unified error handling system used throughout the envy project. It includes features such as custom error types, error messages, retry mechanisms, timeout handling, and more.

Main Features

1. Custom Error Type (EnvyError)
// Create error
err := errors.New(errors.ErrConfigNotFound, "Configuration file not found")
    .WithDetails("file", ".envyrc")
    .WithRetriable(false)

// Check error type
if errors.IsConfigError(err) {
    // Handle configuration-related errors
}
2. Error Categories
  • Configuration Errors (ErrConfig*): Configuration file related
  • Validation Errors (ErrValidation*): Input validation related
  • AWS Errors (ErrAWS*): AWS API related
  • File Errors (ErrFile*): File operation related
  • Network Errors (ErrNetwork*): Network related
3. User Messages
// User-friendly messages
fmt.Println(err.UserMessage())
// Output: "Configuration file not found. Please run 'envy init' command to initialize."
4. Error Formatters
// Standard error output
errors.PrintError(err)

// Verbose error output
errors.PrintErrorVerbose(err)

// Error with context
errors.FormatWithContext(err, errors.ErrorContext{
    Operation:   "AWS Sync",
    Environment: "production",
    Region:      "ap-northeast-1",
})
5. Error Aggregation
aggregator := errors.NewAggregator()

for _, file := range files {
    if err := processFile(file); err != nil {
        aggregator.Add(err)
    }
}

if aggregator.HasErrors() {
    return aggregator.Error()
}

Retry Mechanism

Basic Usage
// Retry with default settings
err := retry.WithRetry(ctx, func() error {
    return someOperation()
})

// Retry with AWS settings
err := retry.WithAWSRetry(ctx, func() error {
    return awsClient.GetParameter(name)
})

// Retry with custom settings
retryer := retry.New(retry.Config{
    MaxAttempts:  5,
    InitialDelay: 1 * time.Second,
    MaxDelay:     30 * time.Second,
    Strategy:     retry.StrategyExponential,
})

err := retryer.Do(ctx, func(ctx context.Context) error {
    return someOperation()
})
Retry Notifications
err := retryer.DoWithNotify(ctx, operation, func(err error, attempt int, delay time.Duration) {
    log.Printf("Retry %d/%d: %v (next: %s)", attempt, maxAttempts, err, delay)
})

Timeout Handling

// Operation-specific timeout
err := retry.WithAWSTimeout(ctx, func(ctx context.Context) error {
    return awsOperation(ctx)
})

err := retry.WithNetworkTimeout(ctx, func(ctx context.Context) error {
    return httpClient.Do(req)
})

// Custom timeout
err := retry.WithTimeout(ctx, 30*time.Second, func(ctx context.Context) error {
    return longRunningOperation(ctx)
})

Usage Examples

Command Usage
func (c *PullCommand) Execute(ctx context.Context) error {
    // Input validation
    if c.environment == "" {
        return errors.New(errors.ErrRequiredField, "Environment name is required")
            .WithDetails("field", "environment")
    }

    // AWS operation (with retry)
    params, err := retry.WithAWSRetry(ctx, func() error {
        return c.awsClient.GetParameters(c.environment)
    })
    
    if err != nil {
        // Enhance and return error
        return errors.EnhanceAWSError(err, "GetParameters", c.environment)
    }

    // Success message
    errors.PrintSuccess(fmt.Sprintf("Retrieved %d parameters", len(params)))
    return nil
}
Error Handling Best Practices
  1. Early Return: Return immediately when an error occurs
  2. Add Context: Add operation and resource information to errors
  3. Appropriate Error Types: Use appropriate error codes for the situation
  4. Retriable: Set network and rate limit errors as retriable
  5. User-Friendly: Provide clear and understandable messages

Testing

// Error testing
func TestOperation(t *testing.T) {
    err := someOperation()
    
    // Check error type
    assert.True(t, errors.IsAWSError(err))
    
    // Check error code
    assert.Equal(t, errors.ErrParameterNotFound, errors.GetErrorCode(err))
    
    // Check retriability
    assert.True(t, errors.IsRetriable(err))
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AdaptAWSError

func AdaptAWSError(err error) error

AdaptAWSError converts AWS package errors to internal errors

func EnhanceAWSError

func EnhanceAWSError(err error, operation string, resource string) error

EnhanceAWSError enhances AWS error with operation context

func FormatWithContext

func FormatWithContext(err error, ctx ErrorContext) string

FormatWithContext formats an error with additional context

func GetErrorDetails

func GetErrorDetails(err error) map[string]interface{}

GetErrorDetails extracts error details

func IsAWSError

func IsAWSError(err error) bool

IsAWSError checks if the error is an AWS error

func IsConfigError

func IsConfigError(err error) bool

IsConfigError checks if the error is a configuration error

func IsFileError

func IsFileError(err error) bool

IsFileError checks if the error is a file error

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError checks if the error is a network error

func IsRetriable

func IsRetriable(err error) bool

IsRetriable checks if the error is retriable

func IsValidationError

func IsValidationError(err error) bool

IsValidationError checks if the error is a validation error

func PrintError

func PrintError(err error)

PrintError prints an error to stderr with formatting.

func PrintErrorVerbose

func PrintErrorVerbose(err error)

PrintErrorVerbose prints an error with verbose information.

func PrintInfof

func PrintInfof(format string, args ...interface{})

PrintInfo prints an info message.

func PrintSuccessf

func PrintSuccessf(format string, args ...interface{})

PrintSuccess prints a success message.

func PrintWarning

func PrintWarning(message string)

PrintWarning prints a warning message.

func Wrapf

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

Wrapf wraps an error with formatted message

Types

type EnvyError

type EnvyError struct {
	Code      ErrorCode              `json:"code"`
	Message   string                 `json:"message"`
	Details   map[string]interface{} `json:"details,omitempty"`
	Cause     error                  `json:"-"`
	Timestamp time.Time              `json:"timestamp"`
	Retriable bool                   `json:"retriable"`
}

EnvyError は envy のカスタムエラー型

func AWSError

func AWSError(message string) *EnvyError

AWSError はAWS関連のエラーを作成

func ConfigError

func ConfigError(message string) *EnvyError

ConfigError は設定関連のエラーを作成

func FileError

func FileError(message string) *EnvyError

FileError はファイル関連のエラーを作成

func NetworkError

func NetworkError(message string) *EnvyError

NetworkError はネットワーク関連のエラーを作成

func New

func New(code ErrorCode, message string) *EnvyError

New は新しいEnvyErrorを作成

func ValidationError

func ValidationError(message string) *EnvyError

ValidationError はバリデーション関連のエラーを作成

func Wrap

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

Wrap wraps an existing error with EnvyError

func WrapAWSError

func WrapAWSError(err error, operation string, resource string) *EnvyError

WrapAWSError converts AWS SDK errors to EnvyError

func WrapFileError

func WrapFileError(err error, filepath string) *EnvyError

WrapFileError converts file operation errors to EnvyError

func WrapNetworkError

func WrapNetworkError(err error) *EnvyError

WrapNetworkError converts network errors to EnvyError

func (*EnvyError) Error

func (e *EnvyError) Error() string

Error implements error interface

func (*EnvyError) Is

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

Is implements errors.Is

func (*EnvyError) Unwrap

func (e *EnvyError) Unwrap() error

Unwrap implements errors.Unwrap

func (*EnvyError) UserMessage

func (e *EnvyError) UserMessage() string

UserMessage returns user-friendly error messages

func (*EnvyError) WithCause

func (e *EnvyError) WithCause(cause error) *EnvyError

WithCause は原因となるエラーを設定

func (*EnvyError) WithDetails

func (e *EnvyError) WithDetails(key string, value interface{}) *EnvyError

WithDetails は詳細情報を追加

func (*EnvyError) WithRetriable

func (e *EnvyError) WithRetriable(retriable bool) *EnvyError

WithRetriable はリトライ可能フラグを設定

type ErrorAggregator

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

AggregateErrors combines multiple errors into one

func NewAggregator

func NewAggregator() *ErrorAggregator

NewAggregator creates a new error aggregator

func (*ErrorAggregator) Add

func (a *ErrorAggregator) Add(err error)

Add adds an error to the aggregator

func (*ErrorAggregator) AddWithContext

func (a *ErrorAggregator) AddWithContext(err error, context string)

AddWithContext adds an error with context

func (*ErrorAggregator) Error

func (a *ErrorAggregator) Error() error

Error returns the aggregated error

func (*ErrorAggregator) Errors

func (a *ErrorAggregator) Errors() []error

Errors returns all collected errors

func (*ErrorAggregator) HasErrors

func (a *ErrorAggregator) HasErrors() bool

HasErrors checks if there are any errors

type ErrorCode

type ErrorCode string

ErrorCode represents the type of error

const (
	// Configuration related errors
	ErrConfigNotFound   ErrorCode = "CONFIG_NOT_FOUND"
	ErrConfigInvalid    ErrorCode = "CONFIG_INVALID"
	ErrConfigParse      ErrorCode = "CONFIG_PARSE"
	ErrConfigPermission ErrorCode = "CONFIG_PERMISSION"

	// Validation related errors
	ErrValidationFailed   ErrorCode = "VALIDATION_FAILED"
	ErrInvalidArgument    ErrorCode = "INVALID_ARGUMENT"
	ErrInvalidEnvironment ErrorCode = "INVALID_ENVIRONMENT"
	ErrInvalidKeyFormat   ErrorCode = "INVALID_KEY_FORMAT"
	ErrRequiredField      ErrorCode = "REQUIRED_FIELD"

	// AWS related errors
	ErrAWSAuth           ErrorCode = "AWS_AUTH_FAILED"
	ErrAWSConnection     ErrorCode = "AWS_CONNECTION_FAILED"
	ErrAWSRateLimit      ErrorCode = "AWS_RATE_LIMIT"
	ErrAWSAccessDenied   ErrorCode = "AWS_ACCESS_DENIED"
	ErrParameterNotFound ErrorCode = "PARAMETER_NOT_FOUND"
	ErrSecretNotFound    ErrorCode = "SECRET_NOT_FOUND"
	ErrParameterExists   ErrorCode = "PARAMETER_EXISTS"
	ErrSecretExists      ErrorCode = "SECRET_EXISTS"
	ErrAWSTimeout        ErrorCode = "AWS_TIMEOUT"

	// File related errors
	ErrFileNotFound   ErrorCode = "FILE_NOT_FOUND"
	ErrFilePermission ErrorCode = "FILE_PERMISSION"
	ErrFileRead       ErrorCode = "FILE_READ"
	ErrFileWrite      ErrorCode = "FILE_WRITE"
	ErrFileInvalid    ErrorCode = "FILE_INVALID"

	// Network related errors
	ErrNetworkTimeout     ErrorCode = "NETWORK_TIMEOUT"
	ErrNetworkUnavailable ErrorCode = "NETWORK_UNAVAILABLE"
	ErrDNSResolution      ErrorCode = "DNS_RESOLUTION"

	// System errors
	ErrInternal     ErrorCode = "INTERNAL_ERROR"
	ErrUnknown      ErrorCode = "UNKNOWN_ERROR"
	ErrNotSupported ErrorCode = "NOT_SUPPORTED"
	ErrTimeout      ErrorCode = "TIMEOUT"
	ErrInvalidInput ErrorCode = "INVALID_INPUT"
)

func GetErrorCode

func GetErrorCode(err error) ErrorCode

GetErrorCode extracts the error code from an error

type ErrorContext

type ErrorContext struct {
	Operation   string
	Environment string
	Region      string
	Profile     string
	File        string
}

ErrorContext provides additional context for errors

type Formatter

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

Formatter provides error formatting functionality

func NewFormatter

func NewFormatter(useColor, verbose bool) *Formatter

NewFormatter creates a new error formatter

func (*Formatter) Format

func (f *Formatter) Format(err error) string

Format formats an error for display

func (*Formatter) FormatMultiple

func (f *Formatter) FormatMultiple(errors []error) string

FormatMultiple formats multiple errors

func (*Formatter) FormatShort

func (f *Formatter) FormatShort(err error) string

FormatShort formats an error in a compact way

Jump to

Keyboard shortcuts

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