Documentation
¶
Overview ¶
Package errors provides error categorization and severity management
Package errors provides comprehensive error handling for the CLI application ¶
Package errors provides contextual error messages with actionable suggestions ¶
Package errors provides comprehensive error handling for the CLI application.
This package implements a complete error handling system that includes:
Error Types and Categorization ¶
The package defines various error types for different categories of failures:
- ErrorTypeValidation: Input validation and project structure errors
- ErrorTypeConfiguration: Configuration file and settings errors
- ErrorTypeTemplate: Template processing and management errors
- ErrorTypeNetwork: Network connectivity and API errors
- ErrorTypeFileSystem: File and directory operation errors
- ErrorTypePermission: Permission and access control errors
- ErrorTypeCache: Cache management and storage errors
- ErrorTypeVersion: Version checking and update errors
- ErrorTypeAudit: Security and quality audit errors
- ErrorTypeGeneration: Project generation and processing errors
- ErrorTypeDependency: Dependency management and compatibility errors
- ErrorTypeSecurity: Security vulnerabilities and policy violations
- ErrorTypeUser: User input and interaction errors
- ErrorTypeInternal: Internal system errors and unexpected conditions
Error Severity Levels ¶
Errors are classified by severity to help prioritize resolution:
- SeverityLow: Minor issues that don't prevent operation
- SeverityMedium: Issues that may affect functionality
- SeverityHigh: Serious issues that prevent normal operation
- SeverityCritical: Critical issues requiring immediate attention
Error Recovery ¶
The package includes automatic error recovery mechanisms:
- NetworkRecoveryStrategy: Handles network failures with offline fallback
- FileSystemRecoveryStrategy: Creates missing directories and handles permissions
- CacheRecoveryStrategy: Clears corrupted cache data
- ConfigurationRecoveryStrategy: Creates default configurations
- TemplateRecoveryStrategy: Suggests alternative templates
- ValidationRecoveryStrategy: Provides valid value suggestions
Contextual Error Information ¶
Errors include rich contextual information:
- Command and arguments that caused the error
- Working directory and environment details
- CI/CD environment detection
- File and line number information
- Operation and component context
Error Logging and Reporting ¶
Comprehensive logging and reporting capabilities:
- Structured logging in text or JSON format
- Automatic error report generation
- Error statistics and pattern analysis
- Recovery attempt tracking
- Multiple output formats (text, JSON, HTML)
Usage Examples ¶
Basic error handling:
handler, err := errors.NewErrorHandler(errors.DefaultErrorHandlerConfig())
if err != nil {
log.Fatal(err)
}
defer handler.Close()
// Handle a validation error
result := handler.NewValidationErrorHandler(
"Invalid project name",
"name",
"invalid-name!",
)
if !result.Success {
os.Exit(result.ExitCode)
}
Creating custom errors with context:
err := errors.NewContextualError(errors.ErrorTypeTemplate, "Template not found", errors.ExitCodeTemplateNotFound).
WithOperation("generate").
WithComponent("template-manager").
WithDetail("template_name", "invalid-template").
WithSuggestion("Use 'generator list-templates' to see available templates").
Build()
result := handler.HandleError(err, map[string]interface{}{
"operation": "generate",
"user_input": "invalid-template",
})
Global error handling:
// Initialize global handler
errors.InitializeGlobalErrorHandler(errors.DefaultErrorHandlerConfig())
// Use global handler
result := errors.HandleGlobalError(someError, map[string]interface{}{
"operation": "validate",
})
Error Statistics and Analysis ¶
The package tracks error statistics for analysis:
stats := handler.GetStatistics()
fmt.Printf("Total errors: %d\n", stats.TotalErrors)
fmt.Printf("Recovery rate: %.1f%%\n", stats.RecoveryRate)
report := handler.GenerateAnalysisReport()
// Use report for insights and improvements
Integration with CLI ¶
The error handling system integrates seamlessly with the CLI:
- Automatic context collection from command execution
- CI/CD environment detection and adaptation
- Machine-readable output for automation
- Verbose and quiet mode support
- Exit code management for scripts
Configuration ¶
The error handler can be configured for different environments:
config := &errors.ErrorHandlerConfig{
LogLevel: errors.LogLevelDebug,
LogFormat: "json",
EnableRecovery: true,
EnableReporting: true,
VerboseMode: true,
}
handler, err := errors.NewErrorHandler(config)
Thread Safety ¶
All components in this package are thread-safe and can be used concurrently from multiple goroutines.
Package errors provides a unified error handling system for the CLI application ¶
Package errors provides logger adapters for interface compatibility ¶
Package errors provides comprehensive error logging and reporting ¶
Package errors provides error recovery mechanisms for common failures ¶
Package errors provides security utilities for error handling
Index ¶
- Constants
- func FormatErrorForUser(err *CLIError, verbose bool) string
- func GetCallerInfo(skip int) (string, int)
- func InitializeGlobalErrorHandler(config *ErrorHandlerConfig) error
- func PropagateError(err error, context string) error
- type CIEnvironment
- type CLIError
- func ChainErrors(errors []error, operation string) *CLIError
- func NewAuditError(message string, auditType string, score float64, cause error) *CLIError
- func NewCLIError(errorType, message string, code int) *CLIError
- func NewCacheError(message string, cacheKey string, cause error) *CLIError
- func NewConfigurationError(message string, configPath string, cause error) *CLIError
- func NewDependencyError(message string, dependency string, version string, cause error) *CLIError
- func NewFileSystemError(message string, path string, operation string, cause error) *CLIError
- func NewGenerationError(message string, component string, operation string, cause error) *CLIError
- func NewInternalError(message string, component string, cause error) *CLIError
- func NewNetworkError(message string, url string, cause error) *CLIError
- func NewPermissionError(message string, path string, requiredPermission string, cause error) *CLIError
- func NewSecurityError(message string, securityIssue string, severity string, cause error) *CLIError
- func NewTemplateError(message string, templateName string, cause error) *CLIError
- func NewUserError(message string, userInput string, expectedFormat string) *CLIError
- func NewValidationError(message string, field string, value interface{}) *CLIError
- func NewVersionError(message string, component string, cause error) *CLIError
- func WrapError(err error, errorType string, message string, code int) *CLIError
- func (e *CLIError) Error() string
- func (e *CLIError) ExitCode() int
- func (e *CLIError) GetSeverity() Severity
- func (e *CLIError) IsRecoverable() bool
- func (e *CLIError) ToJSON() ([]byte, error)
- func (e *CLIError) Unwrap() error
- func (e *CLIError) WithCause(cause error) *CLIError
- func (e *CLIError) WithContext(ctx *ErrorContext) *CLIError
- func (e *CLIError) WithDetails(key string, value interface{}) *CLIError
- func (e *CLIError) WithRecoverable(recoverable bool) *CLIError
- func (e *CLIError) WithSeverity(severity Severity) *CLIError
- func (e *CLIError) WithSuggestions(suggestions ...string) *CLIError
- type CacheRecoveryStrategy
- type CallerInfo
- type CategoryAnalysis
- type ConfigurationRecoveryStrategy
- type ContextualErrorBuilder
- func (b *ContextualErrorBuilder) Build() *CLIError
- func (b *ContextualErrorBuilder) WithCause(cause error) *ContextualErrorBuilder
- func (b *ContextualErrorBuilder) WithCommand(command string, args []string, flags map[string]string) *ContextualErrorBuilder
- func (b *ContextualErrorBuilder) WithComponent(component string) *ContextualErrorBuilder
- func (b *ContextualErrorBuilder) WithDetail(key string, value interface{}) *ContextualErrorBuilder
- func (b *ContextualErrorBuilder) WithEnvironment(env string, ci *CIEnvironment) *ContextualErrorBuilder
- func (b *ContextualErrorBuilder) WithFile(file string, line int) *ContextualErrorBuilder
- func (b *ContextualErrorBuilder) WithOperation(operation string) *ContextualErrorBuilder
- func (b *ContextualErrorBuilder) WithRecoverable(recoverable bool) *ContextualErrorBuilder
- func (b *ContextualErrorBuilder) WithSeverity(severity Severity) *ContextualErrorBuilder
- func (b *ContextualErrorBuilder) WithSuggestion(suggestion string) *ContextualErrorBuilder
- func (b *ContextualErrorBuilder) WithWorkingDirectory(dir string) *ContextualErrorBuilder
- type ContextualSuggestionGenerator
- type EnvironmentInfo
- type ErrorAnalysisReport
- type ErrorCategorizer
- func (ec *ErrorCategorizer) CategorizeError(err *CLIError) *ErrorCategory
- func (ec *ErrorCategorizer) GenerateErrorReport() *ErrorAnalysisReport
- func (ec *ErrorCategorizer) GetCategories() map[string]*ErrorCategory
- func (ec *ErrorCategorizer) GetSeverityLevels() []SeverityLevel
- func (ec *ErrorCategorizer) GetStatistics() *ErrorStatistics
- func (ec *ErrorCategorizer) RecordError(err *CLIError)
- func (ec *ErrorCategorizer) RegisterCategory(category *ErrorCategory)
- func (ec *ErrorCategorizer) Reset()
- type ErrorCategory
- type ErrorContext
- type ErrorContextCollector
- type ErrorHandler
- func (eh *ErrorHandler) Close() error
- func (eh *ErrorHandler) GenerateAnalysisReport() *ErrorAnalysisReport
- func (eh *ErrorHandler) GetLogPath() string
- func (eh *ErrorHandler) GetRecoveryHistory() *RecoveryHistory
- func (eh *ErrorHandler) GetReportPath() string
- func (eh *ErrorHandler) GetStatistics() *ErrorStatistics
- func (eh *ErrorHandler) HandleError(err error, context map[string]interface{}) *ErrorHandlingResult
- func (eh *ErrorHandler) NewConfigurationErrorHandler(message, configPath string, cause error) *ErrorHandlingResult
- func (eh *ErrorHandler) NewFileSystemErrorHandler(message, path, operation string, cause error) *ErrorHandlingResult
- func (eh *ErrorHandler) NewGenerationErrorHandler(message, component, operation string, cause error) *ErrorHandlingResult
- func (eh *ErrorHandler) NewNetworkErrorHandler(message, url string, cause error) *ErrorHandlingResult
- func (eh *ErrorHandler) NewTemplateErrorHandler(message, templateName string, cause error) *ErrorHandlingResult
- func (eh *ErrorHandler) NewValidationErrorHandler(message, field string, value interface{}) *ErrorHandlingResult
- func (eh *ErrorHandler) SetLogLevel(level LogLevel)
- func (eh *ErrorHandler) SetQuietMode(quiet bool)
- func (eh *ErrorHandler) SetVerboseMode(verbose bool)
- type ErrorHandlerConfig
- type ErrorHandlingResult
- type ErrorLogData
- type ErrorLogger
- func (el *ErrorLogger) Close() error
- func (el *ErrorLogger) Debug(message string, context map[string]interface{})
- func (el *ErrorLogger) Error(message string, context map[string]interface{})
- func (el *ErrorLogger) Fatal(message string, context map[string]interface{})
- func (el *ErrorLogger) Info(message string, context map[string]interface{})
- func (el *ErrorLogger) LogError(err *CLIError)
- func (el *ErrorLogger) LogRecoveryAttempt(attempt *RecoveryAttempt)
- func (el *ErrorLogger) SetContext(key string, value interface{})
- func (el *ErrorLogger) SetJSONFormat(jsonFormat bool)
- func (el *ErrorLogger) SetLevel(level LogLevel)
- func (el *ErrorLogger) Warn(message string, context map[string]interface{})
- type ErrorPattern
- type ErrorReport
- type ErrorReporter
- func (er *ErrorReporter) GenerateReport(err *CLIError, recovery *RecoveryAttempt, context map[string]interface{}) (*ErrorReport, error)
- func (er *ErrorReporter) GetReportPath() string
- func (er *ErrorReporter) ListReports() ([]string, error)
- func (er *ErrorReporter) SaveReport(report *ErrorReport) (string, error)
- type ErrorStatistics
- type FileSystemRecoveryStrategy
- type LogEntry
- type LogLevel
- type LoggerAdapter
- type NetworkRecoveryStrategy
- type RecoveryAction
- type RecoveryAttempt
- type RecoveryHistory
- func (rh *RecoveryHistory) GetAttempts() []RecoveryAttempt
- func (rh *RecoveryHistory) GetFailedAttempts() []RecoveryAttempt
- func (rh *RecoveryHistory) GetSuccessfulAttempts() []RecoveryAttempt
- func (rh *RecoveryHistory) RecordAttempt(err *CLIError, strategy string, result *RecoveryResult, duration time.Duration)
- type RecoveryLogger
- type RecoveryManager
- type RecoveryResult
- type RecoveryStrategy
- type ReportFormat
- type Severity
- type SeverityAnalysis
- type SeverityLevel
- type SystemInfo
- type TemplateRecoveryStrategy
- type TimeRange
- type ValidationRecoveryStrategy
Examples ¶
Constants ¶
const ( ErrorTypeValidation = "validation" ErrorTypeConfiguration = "configuration" ErrorTypeTemplate = "template" ErrorTypeNetwork = "network" ErrorTypeFileSystem = "filesystem" ErrorTypePermission = "permission" ErrorTypeCache = "cache" ErrorTypeVersion = "version" ErrorTypeAudit = "audit" ErrorTypeGeneration = "generation" ErrorTypeInternal = "internal" ErrorTypeUser = "user" ErrorTypeDependency = "dependency" ErrorTypeSecurity = "security" )
Error type constants
const ( ExitCodeSuccess = 0 ExitCodeGeneral = 1 ExitCodeValidationFailed = 2 ExitCodeConfigurationInvalid = 3 ExitCodeTemplateNotFound = 4 ExitCodeNetworkError = 5 ExitCodeFileSystemError = 6 ExitCodePermissionDenied = 7 ExitCodeCacheError = 8 ExitCodeVersionError = 9 ExitCodeAuditFailed = 10 ExitCodeGenerationFailed = 11 ExitCodeDependencyError = 12 ExitCodeSecurityError = 13 ExitCodeUserError = 14 ExitCodeInternalError = 99 )
Exit code constants
Variables ¶
This section is empty.
Functions ¶
func FormatErrorForUser ¶
FormatErrorForUser formats an error message for user-friendly display
func GetCallerInfo ¶
GetCallerInfo gets information about the caller
func InitializeGlobalErrorHandler ¶
func InitializeGlobalErrorHandler(config *ErrorHandlerConfig) error
InitializeGlobalErrorHandler initializes the global error handler
func PropagateError ¶
PropagateError propagates an error with additional context
Types ¶
type CIEnvironment ¶
type CIEnvironment struct {
IsCI bool `json:"is_ci"`
Provider string `json:"provider,omitempty"`
JobID string `json:"job_id,omitempty"`
BuildID string `json:"build_id,omitempty"`
}
CIEnvironment contains CI-specific information
type CLIError ¶
type CLIError struct {
Type string `json:"type"`
Message string `json:"message"`
Code int `json:"code"`
Details map[string]interface{} `json:"details,omitempty"`
Suggestions []string `json:"suggestions,omitempty"`
Context *ErrorContext `json:"context,omitempty"`
Cause error `json:"cause,omitempty"`
Stack string `json:"stack,omitempty"`
Timestamp time.Time `json:"timestamp"`
Severity Severity `json:"severity"`
Recoverable bool `json:"recoverable"`
}
CLIError represents a comprehensive CLI error with categorization and context
func ChainErrors ¶
ChainErrors combines multiple errors into a single error
func NewAuditError ¶
NewAuditError creates an audit error with standard suggestions
func NewCLIError ¶
NewCLIError creates a new CLI error with comprehensive information
func NewCacheError ¶
NewCacheError creates a cache error with standard suggestions
func NewConfigurationError ¶
NewConfigurationError creates a configuration error with standard suggestions
func NewDependencyError ¶
NewDependencyError creates a dependency error with standard suggestions
func NewFileSystemError ¶
NewFileSystemError creates a filesystem error with standard suggestions
func NewGenerationError ¶
NewGenerationError creates a generation error with standard suggestions
func NewInternalError ¶
NewInternalError creates an internal error with standard suggestions
func NewNetworkError ¶
NewNetworkError creates a network error with standard suggestions
func NewPermissionError ¶
func NewPermissionError(message string, path string, requiredPermission string, cause error) *CLIError
NewPermissionError creates a permission error with standard suggestions
func NewSecurityError ¶
NewSecurityError creates a security error with standard suggestions
func NewTemplateError ¶
NewTemplateError creates a template error with standard suggestions
func NewUserError ¶
NewUserError creates a user error with standard suggestions
func NewValidationError ¶
NewValidationError creates a validation error with standard suggestions
func NewVersionError ¶
NewVersionError creates a version error with standard suggestions
func (*CLIError) GetSeverity ¶
GetSeverity returns the error severity
func (*CLIError) IsRecoverable ¶
IsRecoverable returns whether the error is recoverable
func (*CLIError) WithContext ¶
func (e *CLIError) WithContext(ctx *ErrorContext) *CLIError
WithContext adds context information to the CLI error
func (*CLIError) WithDetails ¶
WithDetails adds details to the CLI error
func (*CLIError) WithRecoverable ¶
WithRecoverable sets whether the error is recoverable
func (*CLIError) WithSeverity ¶
WithSeverity sets the error severity
func (*CLIError) WithSuggestions ¶
WithSuggestions adds actionable suggestions to the CLI error
type CacheRecoveryStrategy ¶
type CacheRecoveryStrategy struct {
// contains filtered or unexported fields
}
CacheRecoveryStrategy handles cache-related errors
func (*CacheRecoveryStrategy) CanRecover ¶
func (s *CacheRecoveryStrategy) CanRecover(err *CLIError) bool
func (*CacheRecoveryStrategy) GetDescription ¶
func (s *CacheRecoveryStrategy) GetDescription() string
func (*CacheRecoveryStrategy) Recover ¶
func (s *CacheRecoveryStrategy) Recover(err *CLIError) (*RecoveryResult, error)
type CallerInfo ¶
type CallerInfo struct {
File string `json:"file"`
Line int `json:"line"`
Function string `json:"function"`
}
CallerInfo contains information about the caller
type CategoryAnalysis ¶
type CategoryAnalysis struct {
Category *ErrorCategory `json:"category"`
Count int `json:"count"`
Percentage float64 `json:"percentage"`
Trend string `json:"trend"` // "increasing", "decreasing", "stable"
}
CategoryAnalysis represents analysis for a specific category
type ConfigurationRecoveryStrategy ¶
type ConfigurationRecoveryStrategy struct {
// contains filtered or unexported fields
}
ConfigurationRecoveryStrategy handles configuration-related errors
func (*ConfigurationRecoveryStrategy) CanRecover ¶
func (s *ConfigurationRecoveryStrategy) CanRecover(err *CLIError) bool
func (*ConfigurationRecoveryStrategy) GetDescription ¶
func (s *ConfigurationRecoveryStrategy) GetDescription() string
func (*ConfigurationRecoveryStrategy) Recover ¶
func (s *ConfigurationRecoveryStrategy) Recover(err *CLIError) (*RecoveryResult, error)
type ContextualErrorBuilder ¶
type ContextualErrorBuilder struct {
// contains filtered or unexported fields
}
ContextualErrorBuilder helps build errors with rich context and suggestions
func NewContextualError ¶
func NewContextualError(errorType, message string, code int) *ContextualErrorBuilder
NewContextualError creates a new contextual error builder
func (*ContextualErrorBuilder) Build ¶
func (b *ContextualErrorBuilder) Build() *CLIError
Build creates the final CLIError
func (*ContextualErrorBuilder) WithCause ¶
func (b *ContextualErrorBuilder) WithCause(cause error) *ContextualErrorBuilder
WithCause adds the underlying cause to the error
func (*ContextualErrorBuilder) WithCommand ¶
func (b *ContextualErrorBuilder) WithCommand(command string, args []string, flags map[string]string) *ContextualErrorBuilder
WithCommand adds command context to the error
func (*ContextualErrorBuilder) WithComponent ¶
func (b *ContextualErrorBuilder) WithComponent(component string) *ContextualErrorBuilder
WithComponent adds component context to the error
func (*ContextualErrorBuilder) WithDetail ¶
func (b *ContextualErrorBuilder) WithDetail(key string, value interface{}) *ContextualErrorBuilder
WithDetail adds a detail to the error
func (*ContextualErrorBuilder) WithEnvironment ¶
func (b *ContextualErrorBuilder) WithEnvironment(env string, ci *CIEnvironment) *ContextualErrorBuilder
WithEnvironment adds environment context to the error
func (*ContextualErrorBuilder) WithFile ¶
func (b *ContextualErrorBuilder) WithFile(file string, line int) *ContextualErrorBuilder
WithFile adds file context to the error
func (*ContextualErrorBuilder) WithOperation ¶
func (b *ContextualErrorBuilder) WithOperation(operation string) *ContextualErrorBuilder
WithOperation adds operation context to the error
func (*ContextualErrorBuilder) WithRecoverable ¶
func (b *ContextualErrorBuilder) WithRecoverable(recoverable bool) *ContextualErrorBuilder
WithRecoverable sets whether the error is recoverable
func (*ContextualErrorBuilder) WithSeverity ¶
func (b *ContextualErrorBuilder) WithSeverity(severity Severity) *ContextualErrorBuilder
WithSeverity sets the error severity
func (*ContextualErrorBuilder) WithSuggestion ¶
func (b *ContextualErrorBuilder) WithSuggestion(suggestion string) *ContextualErrorBuilder
WithSuggestion adds a suggestion to the error
func (*ContextualErrorBuilder) WithWorkingDirectory ¶
func (b *ContextualErrorBuilder) WithWorkingDirectory(dir string) *ContextualErrorBuilder
WithWorkingDirectory adds working directory context
type ContextualSuggestionGenerator ¶
type ContextualSuggestionGenerator struct{}
ContextualSuggestionGenerator generates contextual suggestions based on error details
func NewContextualSuggestionGenerator ¶
func NewContextualSuggestionGenerator() *ContextualSuggestionGenerator
NewContextualSuggestionGenerator creates a new suggestion generator
func (*ContextualSuggestionGenerator) GenerateSuggestions ¶
func (g *ContextualSuggestionGenerator) GenerateSuggestions(err *CLIError) []string
GenerateSuggestions generates contextual suggestions for an error
type EnvironmentInfo ¶
type EnvironmentInfo struct {
GeneratorVersion string `json:"generator_version"`
GoVersion string `json:"go_version"`
OS string `json:"os"`
Arch string `json:"arch"`
WorkingDir string `json:"working_dir"`
Environment map[string]string `json:"environment"`
CI *CIEnvironment `json:"ci,omitempty"`
}
EnvironmentInfo contains environment information for reports
type ErrorAnalysisReport ¶
type ErrorAnalysisReport struct {
GeneratedAt time.Time `json:"generated_at"`
TotalErrors int `json:"total_errors"`
RecoveryRate float64 `json:"recovery_rate"`
Categories []CategoryAnalysis `json:"categories"`
SeverityBreakdown []SeverityAnalysis `json:"severity_breakdown"`
TopPatterns []ErrorPattern `json:"top_patterns"`
Recommendations []string `json:"recommendations"`
TimeRange *TimeRange `json:"time_range"`
}
ErrorAnalysisReport represents a comprehensive error analysis report
type ErrorCategorizer ¶
type ErrorCategorizer struct {
// contains filtered or unexported fields
}
ErrorCategorizer manages error categorization and analysis
func NewErrorCategorizer ¶
func NewErrorCategorizer() *ErrorCategorizer
NewErrorCategorizer creates a new error categorizer with default categories
func (*ErrorCategorizer) CategorizeError ¶
func (ec *ErrorCategorizer) CategorizeError(err *CLIError) *ErrorCategory
CategorizeError categorizes an error and returns the category
func (*ErrorCategorizer) GenerateErrorReport ¶
func (ec *ErrorCategorizer) GenerateErrorReport() *ErrorAnalysisReport
GenerateErrorReport generates a comprehensive error analysis report
func (*ErrorCategorizer) GetCategories ¶
func (ec *ErrorCategorizer) GetCategories() map[string]*ErrorCategory
GetCategories returns all registered categories
func (*ErrorCategorizer) GetSeverityLevels ¶
func (ec *ErrorCategorizer) GetSeverityLevels() []SeverityLevel
GetSeverityLevels returns detailed information about severity levels
func (*ErrorCategorizer) GetStatistics ¶
func (ec *ErrorCategorizer) GetStatistics() *ErrorStatistics
GetStatistics returns current error statistics
func (*ErrorCategorizer) RecordError ¶
func (ec *ErrorCategorizer) RecordError(err *CLIError)
RecordError records an error for statistical analysis
func (*ErrorCategorizer) RegisterCategory ¶
func (ec *ErrorCategorizer) RegisterCategory(category *ErrorCategory)
RegisterCategory registers a new error category
func (*ErrorCategorizer) Reset ¶
func (ec *ErrorCategorizer) Reset()
Reset resets all error statistics
type ErrorCategory ¶
type ErrorCategory struct {
Name string `json:"name"`
Description string `json:"description"`
Types []string `json:"types"`
Severity Severity `json:"default_severity"`
Recoverable bool `json:"default_recoverable"`
}
ErrorCategory represents a category of errors for better organization
type ErrorContext ¶
type ErrorContext struct {
Command string `json:"command"`
Arguments []string `json:"arguments"`
Flags map[string]string `json:"flags"`
WorkingDir string `json:"working_dir"`
Environment string `json:"environment,omitempty"`
CI *CIEnvironment `json:"ci,omitempty"`
Operation string `json:"operation,omitempty"`
Component string `json:"component,omitempty"`
File string `json:"file,omitempty"`
Line int `json:"line,omitempty"`
}
ErrorContext provides detailed context information for errors
type ErrorContextCollector ¶
type ErrorContextCollector struct{}
ErrorContextCollector collects context information for errors
func NewErrorContextCollector ¶
func NewErrorContextCollector() *ErrorContextCollector
NewErrorContextCollector creates a new context collector
func (*ErrorContextCollector) CollectCommandContext ¶
func (c *ErrorContextCollector) CollectCommandContext(command string, args []string, flags map[string]string) *ErrorContext
CollectCommandContext collects context for a specific command
func (*ErrorContextCollector) CollectContext ¶
func (c *ErrorContextCollector) CollectContext() *ErrorContext
CollectContext collects comprehensive context information
type ErrorHandler ¶
type ErrorHandler struct {
// contains filtered or unexported fields
}
ErrorHandler provides a unified interface for comprehensive error handling
Example ¶
Example demonstrates basic usage of the error handling system
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/cuesoftinc/open-source-project-generator/pkg/errors"
)
func main() {
// Create a temporary directory for testing
tempDir, _ := os.MkdirTemp("", "error-handler-test")
defer func() { _ = os.RemoveAll(tempDir) }()
// Configure error handler
config := &errors.ErrorHandlerConfig{
LogLevel: errors.LogLevelInfo,
LogFormat: "text",
LogPath: filepath.Join(tempDir, "test.log"),
ReportPath: filepath.Join(tempDir, "reports"),
ReportFormat: errors.ReportFormatText,
MaxReports: 10,
EnableRecovery: true,
EnableReporting: true,
VerboseMode: false,
QuietMode: true, // Quiet for test
}
// Create error handler
handler, err := errors.NewErrorHandler(config)
if err != nil {
fmt.Printf("Failed to create error handler: %v\n", err)
return
}
defer func() { _ = handler.Close() }()
// Create a validation error
validationErr := errors.NewValidationError(
"Invalid project name format",
"project_name",
"invalid-name!",
)
// Handle the error
result := handler.HandleError(validationErr, map[string]interface{}{
"operation": "project_validation",
"user_id": "test-user",
})
// Check results
fmt.Printf("Error handled successfully: %t\n", result.Error != nil)
fmt.Printf("Error type: %s\n", result.Error.Type)
fmt.Printf("Error severity: %s\n", result.Error.Severity)
fmt.Printf("Error recoverable: %t\n", result.Error.Recoverable)
fmt.Printf("Suggestions provided: %t\n", len(result.Suggestions) > 0)
}
Output: Error handled successfully: true Error type: validation Error severity: medium Error recoverable: true Suggestions provided: true
func GetGlobalErrorHandler ¶
func GetGlobalErrorHandler() *ErrorHandler
GetGlobalErrorHandler returns the global error handler
func NewErrorHandler ¶
func NewErrorHandler(config *ErrorHandlerConfig) (*ErrorHandler, error)
NewErrorHandler creates a new comprehensive error handler
func (*ErrorHandler) Close ¶
func (eh *ErrorHandler) Close() error
Close closes the error handler and releases resources
func (*ErrorHandler) GenerateAnalysisReport ¶
func (eh *ErrorHandler) GenerateAnalysisReport() *ErrorAnalysisReport
GenerateAnalysisReport generates a comprehensive error analysis report
func (*ErrorHandler) GetLogPath ¶
func (eh *ErrorHandler) GetLogPath() string
GetLogPath returns the path to the log file
func (*ErrorHandler) GetRecoveryHistory ¶
func (eh *ErrorHandler) GetRecoveryHistory() *RecoveryHistory
GetRecoveryHistory returns recovery history
func (*ErrorHandler) GetReportPath ¶
func (eh *ErrorHandler) GetReportPath() string
GetReportPath returns the path to the report directory
func (*ErrorHandler) GetStatistics ¶
func (eh *ErrorHandler) GetStatistics() *ErrorStatistics
GetStatistics returns error statistics
func (*ErrorHandler) HandleError ¶
func (eh *ErrorHandler) HandleError(err error, context map[string]interface{}) *ErrorHandlingResult
HandleError is the main entry point for handling errors
func (*ErrorHandler) NewConfigurationErrorHandler ¶
func (eh *ErrorHandler) NewConfigurationErrorHandler(message, configPath string, cause error) *ErrorHandlingResult
NewConfigurationErrorHandler creates a configuration error and handles it
func (*ErrorHandler) NewFileSystemErrorHandler ¶
func (eh *ErrorHandler) NewFileSystemErrorHandler(message, path, operation string, cause error) *ErrorHandlingResult
NewFileSystemErrorHandler creates a filesystem error and handles it
func (*ErrorHandler) NewGenerationErrorHandler ¶
func (eh *ErrorHandler) NewGenerationErrorHandler(message, component, operation string, cause error) *ErrorHandlingResult
NewGenerationErrorHandler creates a generation error and handles it
func (*ErrorHandler) NewNetworkErrorHandler ¶
func (eh *ErrorHandler) NewNetworkErrorHandler(message, url string, cause error) *ErrorHandlingResult
NewNetworkErrorHandler creates a network error and handles it
func (*ErrorHandler) NewTemplateErrorHandler ¶
func (eh *ErrorHandler) NewTemplateErrorHandler(message, templateName string, cause error) *ErrorHandlingResult
NewTemplateErrorHandler creates a template error and handles it
func (*ErrorHandler) NewValidationErrorHandler ¶
func (eh *ErrorHandler) NewValidationErrorHandler(message, field string, value interface{}) *ErrorHandlingResult
NewValidationErrorHandler creates a validation error and handles it
func (*ErrorHandler) SetLogLevel ¶
func (eh *ErrorHandler) SetLogLevel(level LogLevel)
SetLogLevel sets the logging level
func (*ErrorHandler) SetQuietMode ¶
func (eh *ErrorHandler) SetQuietMode(quiet bool)
SetQuietMode sets quiet mode
func (*ErrorHandler) SetVerboseMode ¶
func (eh *ErrorHandler) SetVerboseMode(verbose bool)
SetVerboseMode sets verbose mode
type ErrorHandlerConfig ¶
type ErrorHandlerConfig struct {
LogLevel LogLevel `json:"log_level"`
LogFormat string `json:"log_format"` // "text" or "json"
LogPath string `json:"log_path"`
ReportPath string `json:"report_path"`
ReportFormat ReportFormat `json:"report_format"`
MaxReports int `json:"max_reports"`
EnableRecovery bool `json:"enable_recovery"`
EnableReporting bool `json:"enable_reporting"`
VerboseMode bool `json:"verbose_mode"`
QuietMode bool `json:"quiet_mode"`
AutoGenerateID bool `json:"auto_generate_id"`
}
ErrorHandlerConfig contains configuration for the error handler
func DefaultErrorHandlerConfig ¶
func DefaultErrorHandlerConfig() *ErrorHandlerConfig
DefaultErrorHandlerConfig returns a default configuration
type ErrorHandlingResult ¶
type ErrorHandlingResult struct {
Success bool `json:"success"`
Error *CLIError `json:"error"`
Recovery *RecoveryResult `json:"recovery,omitempty"`
ReportPath string `json:"report_path,omitempty"`
Duration time.Duration `json:"duration"`
Suggestions []string `json:"suggestions"`
Category *ErrorCategory `json:"category"`
ExitCode int `json:"exit_code"`
}
ErrorHandlingResult represents the result of error handling
func HandleGlobalError ¶
func HandleGlobalError(err error, context map[string]interface{}) *ErrorHandlingResult
HandleGlobalError handles an error using the global error handler
type ErrorLogData ¶
type ErrorLogData struct {
Type string `json:"type"`
Code int `json:"code"`
Message string `json:"message"`
Details map[string]interface{} `json:"details,omitempty"`
Suggestions []string `json:"suggestions,omitempty"`
Context *ErrorContext `json:"context,omitempty"`
Cause string `json:"cause,omitempty"`
Stack string `json:"stack,omitempty"`
Severity string `json:"severity"`
Recoverable bool `json:"recoverable"`
}
ErrorLogData contains detailed error information for logging
type ErrorLogger ¶
type ErrorLogger struct {
// contains filtered or unexported fields
}
ErrorLogger provides comprehensive error logging capabilities
func NewErrorLogger ¶
func NewErrorLogger(logPath string, level LogLevel, jsonFormat bool) (*ErrorLogger, error)
NewErrorLogger creates a new error logger
func (*ErrorLogger) Debug ¶
func (el *ErrorLogger) Debug(message string, context map[string]interface{})
Debug logs a debug message
func (*ErrorLogger) Error ¶
func (el *ErrorLogger) Error(message string, context map[string]interface{})
Error logs an error message
func (*ErrorLogger) Fatal ¶
func (el *ErrorLogger) Fatal(message string, context map[string]interface{})
Fatal logs a fatal message
func (*ErrorLogger) Info ¶
func (el *ErrorLogger) Info(message string, context map[string]interface{})
Info logs an info message
func (*ErrorLogger) LogError ¶
func (el *ErrorLogger) LogError(err *CLIError)
LogError logs a CLI error with full context
func (*ErrorLogger) LogRecoveryAttempt ¶
func (el *ErrorLogger) LogRecoveryAttempt(attempt *RecoveryAttempt)
LogRecoveryAttempt logs a recovery attempt
func (*ErrorLogger) SetContext ¶
func (el *ErrorLogger) SetContext(key string, value interface{})
SetContext sets global context for all log entries
func (*ErrorLogger) SetJSONFormat ¶
func (el *ErrorLogger) SetJSONFormat(jsonFormat bool)
SetJSONFormat sets whether to use JSON format
func (*ErrorLogger) SetLevel ¶
func (el *ErrorLogger) SetLevel(level LogLevel)
SetLevel sets the logging level
func (*ErrorLogger) Warn ¶
func (el *ErrorLogger) Warn(message string, context map[string]interface{})
Warn logs a warning message
type ErrorPattern ¶
type ErrorPattern struct {
Pattern string `json:"pattern"`
Count int `json:"count"`
Percentage float64 `json:"percentage"`
Suggestions []string `json:"suggestions"`
}
ErrorPattern represents a common error pattern
type ErrorReport ¶
type ErrorReport struct {
ID string `json:"id"`
Timestamp time.Time `json:"timestamp"`
Error *CLIError `json:"error"`
Environment *EnvironmentInfo `json:"environment"`
System *SystemInfo `json:"system"`
Recovery *RecoveryAttempt `json:"recovery,omitempty"`
Logs []LogEntry `json:"logs,omitempty"`
Context map[string]interface{} `json:"context,omitempty"`
}
ErrorReport represents a comprehensive error report
type ErrorReporter ¶
type ErrorReporter struct {
// contains filtered or unexported fields
}
ErrorReporter provides error reporting capabilities for debugging and support
func NewErrorReporter ¶
func NewErrorReporter(logger *ErrorLogger, reportDir string, maxReports int, format ReportFormat) *ErrorReporter
NewErrorReporter creates a new error reporter
func (*ErrorReporter) GenerateReport ¶
func (er *ErrorReporter) GenerateReport(err *CLIError, recovery *RecoveryAttempt, context map[string]interface{}) (*ErrorReport, error)
GenerateReport generates a comprehensive error report
func (*ErrorReporter) GetReportPath ¶
func (er *ErrorReporter) GetReportPath() string
GetReportPath returns the path where reports are stored
func (*ErrorReporter) ListReports ¶
func (er *ErrorReporter) ListReports() ([]string, error)
ListReports returns a list of available error reports
func (*ErrorReporter) SaveReport ¶
func (er *ErrorReporter) SaveReport(report *ErrorReport) (string, error)
SaveReport saves an error report to disk
type ErrorStatistics ¶
type ErrorStatistics struct {
TotalErrors int `json:"total_errors"`
ErrorsByType map[string]int `json:"errors_by_type"`
ErrorsByCategory map[string]int `json:"errors_by_category"`
ErrorsBySeverity map[string]int `json:"errors_by_severity"`
ErrorsByHour map[string]int `json:"errors_by_hour"`
RecentErrors []*CLIError `json:"recent_errors"`
FirstError *time.Time `json:"first_error,omitempty"`
LastError *time.Time `json:"last_error,omitempty"`
RecoveryRate float64 `json:"recovery_rate"`
CommonPatterns []ErrorPattern `json:"common_patterns"`
}
ErrorStatistics tracks error statistics for analysis
type FileSystemRecoveryStrategy ¶
type FileSystemRecoveryStrategy struct {
// contains filtered or unexported fields
}
FileSystemRecoveryStrategy handles filesystem-related errors
func (*FileSystemRecoveryStrategy) CanRecover ¶
func (s *FileSystemRecoveryStrategy) CanRecover(err *CLIError) bool
func (*FileSystemRecoveryStrategy) GetDescription ¶
func (s *FileSystemRecoveryStrategy) GetDescription() string
func (*FileSystemRecoveryStrategy) Recover ¶
func (s *FileSystemRecoveryStrategy) Recover(err *CLIError) (*RecoveryResult, error)
type LogEntry ¶
type LogEntry struct {
Timestamp time.Time `json:"timestamp"`
Level string `json:"level"`
Message string `json:"message"`
Error *ErrorLogData `json:"error,omitempty"`
Context map[string]interface{} `json:"context,omitempty"`
Caller *CallerInfo `json:"caller,omitempty"`
}
LogEntry represents a single log entry
type LoggerAdapter ¶
type LoggerAdapter struct {
// contains filtered or unexported fields
}
LoggerAdapter adapts ErrorLogger to RecoveryLogger interface
func NewLoggerAdapter ¶
func NewLoggerAdapter(logger *ErrorLogger) *LoggerAdapter
NewLoggerAdapter creates a new logger adapter
func (*LoggerAdapter) Debug ¶
func (la *LoggerAdapter) Debug(format string, args ...interface{})
Debug logs a debug message
func (*LoggerAdapter) Error ¶
func (la *LoggerAdapter) Error(format string, args ...interface{})
Error logs an error message
func (*LoggerAdapter) Info ¶
func (la *LoggerAdapter) Info(format string, args ...interface{})
Info logs an info message
func (*LoggerAdapter) Warn ¶
func (la *LoggerAdapter) Warn(format string, args ...interface{})
Warn logs a warning message
type NetworkRecoveryStrategy ¶
type NetworkRecoveryStrategy struct {
// contains filtered or unexported fields
}
NetworkRecoveryStrategy handles network-related errors
func (*NetworkRecoveryStrategy) CanRecover ¶
func (s *NetworkRecoveryStrategy) CanRecover(err *CLIError) bool
func (*NetworkRecoveryStrategy) GetDescription ¶
func (s *NetworkRecoveryStrategy) GetDescription() string
func (*NetworkRecoveryStrategy) Recover ¶
func (s *NetworkRecoveryStrategy) Recover(err *CLIError) (*RecoveryResult, error)
type RecoveryAction ¶
type RecoveryAction struct {
Type string `json:"type"`
Description string `json:"description"`
Success bool `json:"success"`
Details map[string]interface{} `json:"details,omitempty"`
}
RecoveryAction represents an action taken during recovery
type RecoveryAttempt ¶
type RecoveryAttempt struct {
Error *CLIError `json:"error"`
Strategy string `json:"strategy"`
Result *RecoveryResult `json:"result"`
StartTime time.Time `json:"start_time"`
Duration time.Duration `json:"duration"`
}
RecoveryAttempt represents a single recovery attempt with timing
type RecoveryHistory ¶
type RecoveryHistory struct {
// contains filtered or unexported fields
}
RecoveryHistory tracks recovery attempts for analysis
func NewRecoveryHistory ¶
func NewRecoveryHistory() *RecoveryHistory
NewRecoveryHistory creates a new recovery history tracker
func (*RecoveryHistory) GetAttempts ¶
func (rh *RecoveryHistory) GetAttempts() []RecoveryAttempt
GetAttempts returns all recovery attempts
func (*RecoveryHistory) GetFailedAttempts ¶
func (rh *RecoveryHistory) GetFailedAttempts() []RecoveryAttempt
GetFailedAttempts returns only failed recovery attempts
func (*RecoveryHistory) GetSuccessfulAttempts ¶
func (rh *RecoveryHistory) GetSuccessfulAttempts() []RecoveryAttempt
GetSuccessfulAttempts returns only successful recovery attempts
func (*RecoveryHistory) RecordAttempt ¶
func (rh *RecoveryHistory) RecordAttempt(err *CLIError, strategy string, result *RecoveryResult, duration time.Duration)
RecordAttempt records a recovery attempt
type RecoveryLogger ¶
type RecoveryLogger interface {
Info(format string, args ...interface{})
Warn(format string, args ...interface{})
Error(format string, args ...interface{})
Debug(format string, args ...interface{})
}
RecoveryLogger interface for recovery logging
type RecoveryManager ¶
type RecoveryManager struct {
// contains filtered or unexported fields
}
RecoveryManager manages error recovery strategies
func NewRecoveryManager ¶
func NewRecoveryManager(logger RecoveryLogger) *RecoveryManager
NewRecoveryManager creates a new recovery manager with default strategies
func (*RecoveryManager) AttemptRecovery ¶
func (rm *RecoveryManager) AttemptRecovery(err *CLIError) (*RecoveryResult, error)
AttemptRecovery attempts to recover from the given error
func (*RecoveryManager) RegisterStrategy ¶
func (rm *RecoveryManager) RegisterStrategy(strategy RecoveryStrategy)
RegisterStrategy registers a new recovery strategy
type RecoveryResult ¶
type RecoveryResult struct {
Success bool `json:"success"`
Message string `json:"message"`
Actions []RecoveryAction `json:"actions"`
Suggestions []string `json:"suggestions"`
Details map[string]interface{} `json:"details,omitempty"`
}
RecoveryResult represents the result of a recovery attempt
type RecoveryStrategy ¶
type RecoveryStrategy interface {
// CanRecover determines if this strategy can recover from the given error
CanRecover(err *CLIError) bool
// Recover attempts to recover from the error
Recover(err *CLIError) (*RecoveryResult, error)
// GetDescription returns a description of what this strategy does
GetDescription() string
}
RecoveryStrategy represents a strategy for recovering from an error
type ReportFormat ¶
type ReportFormat string
ReportFormat represents the format for error reports
const ( ReportFormatText ReportFormat = "text" ReportFormatJSON ReportFormat = "json" ReportFormatHTML ReportFormat = "html" )
type SeverityAnalysis ¶
type SeverityAnalysis struct {
Severity SeverityLevel `json:"severity"`
Count int `json:"count"`
Percentage float64 `json:"percentage"`
}
SeverityAnalysis represents analysis for a specific severity level
type SeverityLevel ¶
type SeverityLevel struct {
Level Severity `json:"level"`
Name string `json:"name"`
Description string `json:"description"`
Color string `json:"color"`
Icon string `json:"icon"`
Priority int `json:"priority"`
}
SeverityLevel provides detailed severity information
type SystemInfo ¶
type SystemInfo struct {
Hostname string `json:"hostname"`
Username string `json:"username"`
ProcessID int `json:"process_id"`
ParentPID int `json:"parent_pid"`
MemoryUsage int64 `json:"memory_usage"`
DiskSpace int64 `json:"disk_space"`
CPUCount int `json:"cpu_count"`
}
SystemInfo contains system information for reports
type TemplateRecoveryStrategy ¶
type TemplateRecoveryStrategy struct {
// contains filtered or unexported fields
}
TemplateRecoveryStrategy handles template-related errors
func (*TemplateRecoveryStrategy) CanRecover ¶
func (s *TemplateRecoveryStrategy) CanRecover(err *CLIError) bool
func (*TemplateRecoveryStrategy) GetDescription ¶
func (s *TemplateRecoveryStrategy) GetDescription() string
func (*TemplateRecoveryStrategy) Recover ¶
func (s *TemplateRecoveryStrategy) Recover(err *CLIError) (*RecoveryResult, error)
type ValidationRecoveryStrategy ¶
type ValidationRecoveryStrategy struct {
// contains filtered or unexported fields
}
ValidationRecoveryStrategy handles validation-related errors
func (*ValidationRecoveryStrategy) CanRecover ¶
func (s *ValidationRecoveryStrategy) CanRecover(err *CLIError) bool
func (*ValidationRecoveryStrategy) GetDescription ¶
func (s *ValidationRecoveryStrategy) GetDescription() string
func (*ValidationRecoveryStrategy) Recover ¶
func (s *ValidationRecoveryStrategy) Recover(err *CLIError) (*RecoveryResult, error)