Documentation
¶
Overview ¶
Package errors provides CLI error handling utilities that map API errors to user-friendly messages and appropriate exit codes.
Exit codes follow POSIX conventions with extensions for specific error types:
0 - Success 1 - General error 2 - Misuse (invalid arguments, configuration) 3 - Authentication required 4 - Permission denied 5 - Resource not found 6 - Rate limited 7 - Server error
Usage:
if err := doSomething(); err != nil {
code := errors.HandleError(err)
os.Exit(code)
}
Package errors provides CLI error handling and formatting utilities.
Package errors provides CLI error handling utilities.
Index ¶
- Constants
- Variables
- func ExitCodeName(code int) string
- func GetSuggestion(errorType string) string
- func GetUserFriendlyMessage(errorCode string, defaultMsg string) string
- func HandleError(err error) int
- func InvalidValueError(flagName, value string, validOptions []string) error
- func InvalidValueWithHintError(flagName, value, hint string) error
- func RequiredArgError(argName string) error
- func RequiredFlagError(flagName string) error
- func SetErrWriter(w io.Writer)
- func SuggestFromOptions(input string, validOptions []string, maxDistance int) string
- type ErrorFormatter
- func (f *ErrorFormatter) FormatError(msg string) string
- func (f *ErrorFormatter) FormatInfo(msg string) string
- func (f *ErrorFormatter) FormatSuccess(msg string) string
- func (f *ErrorFormatter) FormatWarning(msg string) string
- func (f *ErrorFormatter) PrintContext(key, value string)
- func (f *ErrorFormatter) PrintError(msg string)
- func (f *ErrorFormatter) PrintHint(hint string)
- func (f *ErrorFormatter) PrintRequestID(requestID string)
- func (f *ErrorFormatter) PrintSuggestion(text string)
- func (f *ErrorFormatter) PrintValidationErrors(fields map[string]string)
- func (f *ErrorFormatter) PrintWarning(msg string)
- type ErrorWithContext
- type Suggestion
Constants ¶
const ( // ExitSuccess indicates successful completion. ExitSuccess = 0 // ExitError indicates a general error occurred. ExitError = 1 // ExitMisuse indicates command line misuse (invalid arguments, bad config). ExitMisuse = 2 // ExitAuth indicates authentication is required or credentials are invalid. ExitAuth = 3 // ExitForbidden indicates permission was denied for the operation. ExitForbidden = 4 // ExitNotFound indicates the requested resource was not found. ExitNotFound = 5 // ExitRateLimited indicates the request was rate limited. ExitRateLimited = 6 // ExitServerError indicates a server-side error occurred. ExitServerError = 7 // ExitNetwork indicates a network connectivity error. ExitNetwork = 8 // ExitTimeout indicates the operation timed out. ExitTimeout = 9 // ExitPlanLimit indicates a plan limit was exceeded. ExitPlanLimit = 10 // ExitSIGINT indicates the process was interrupted by Ctrl+C (128 + signal 2). // This follows POSIX convention for signal-terminated processes. ExitSIGINT = 130 // ExitSIGTERM indicates the process was terminated by SIGTERM (128 + signal 15). // This follows POSIX convention for signal-terminated processes. ExitSIGTERM = 143 )
Exit codes for CLI operations. These follow POSIX conventions with extensions for StackEye-specific errors.
Variables ¶
var APIErrorMessages = map[string]string{
"unauthorized": "Authentication required.",
"expired_token": "Your session has expired.",
"invalid_api_key": "Invalid API key.",
"invalid_token": "Invalid authentication token.",
"token_revoked": "Your token has been revoked.",
"mfa_required": "Multi-factor authentication required.",
"account_locked": "Account locked due to too many failed attempts.",
"account_disabled": "Your account has been disabled.",
"password_expired": "Your password has expired.",
"session_invalid": "Your session is no longer valid.",
"device_not_trusted": "This device is not trusted.",
"ip_blocked": "Your IP address has been blocked.",
"geo_blocked": "Access from your location is restricted.",
"forbidden": "Permission denied.",
"insufficient_scope": "Your API key lacks the required permissions.",
"read_only": "This resource is read-only.",
"owner_only": "Only the owner can perform this action.",
"admin_required": "Admin privileges required.",
"role_required": "Insufficient role permissions.",
"org_mismatch": "Resource belongs to a different organization.",
"team_mismatch": "Resource belongs to a different team.",
"not_member": "You are not a member of this organization.",
"invitation_only": "Access requires an invitation.",
"not_found": "Resource not found.",
"already_exists": "Resource already exists.",
"conflict": "Resource conflict detected.",
"gone": "Resource has been deleted.",
"locked": "Resource is locked.",
"archived": "Resource has been archived.",
"suspended": "Resource has been suspended.",
"version_mismatch": "Resource version mismatch.",
"stale": "Resource data is stale.",
"rate_limited": "Rate limit exceeded.",
"quota_exceeded": "API quota exceeded.",
"too_many_requests": "Too many requests.",
"burst_exceeded": "Request burst limit exceeded.",
"plan_limit_exceeded": "Plan limit exceeded.",
"probe_limit_exceeded": "Probe limit reached.",
"team_limit_exceeded": "Team member limit reached.",
"channel_limit_exceeded": "Notification channel limit reached.",
"feature_not_available": "Feature not available on your plan.",
"upgrade_required": "Plan upgrade required.",
"trial_expired": "Trial period has expired.",
"subscription_inactive": "Subscription is inactive.",
"payment_required": "Payment required to continue.",
"payment_failed": "Payment processing failed.",
"billing_issue": "Billing issue detected.",
"validation": "Invalid request.",
"invalid_input": "Invalid input provided.",
"malformed_json": "Malformed JSON in request body.",
"missing_field": "Required field is missing.",
"invalid_field": "Field value is invalid.",
"field_too_long": "Field value exceeds maximum length.",
"field_too_short": "Field value is below minimum length.",
"invalid_format": "Invalid format.",
"out_of_range": "Value is out of allowed range.",
"constraint_violation": "Constraint violation.",
"internal_server": "Internal server error.",
"service_unavailable": "Service temporarily unavailable.",
"bad_gateway": "Bad gateway error.",
"gateway_timeout": "Gateway timeout.",
"maintenance": "Service under maintenance.",
"overloaded": "Service is overloaded.",
"database_error": "Database error occurred.",
"upstream_error": "Upstream service error.",
"configuration_error": "Service configuration error.",
"dependency_failure": "Dependent service failure.",
}
APIErrorMessages maps API error codes to user-friendly messages. These provide clearer context than the raw API error messages.
var CommonSuggestions = map[string]string{}/* 157 elements not displayed */
CommonSuggestions provides standard suggestions for common error scenarios. These are used to provide helpful hints to users when errors occur.
var ValidAlertStatuses = []string{"active", "acknowledged", "resolved"}
ValidAlertStatuses contains the valid alert statuses.
var ValidBoolStrings = []string{"true", "false"}
ValidBoolStrings contains valid boolean string values.
var ValidChannelTypes = []string{"email", "slack", "webhook", "pagerduty", "discord", "teams", "sms"}
ValidChannelTypes contains the valid notification channel types.
var ValidCheckTypes = []string{"http", "ping", "tcp", "dns_resolve"}
ValidCheckTypes contains the valid probe check types.
var ValidDependencyDirections = []string{"parents", "children", "both"}
ValidDependencyDirections contains the valid probe dependency clear directions.
var ValidExportFormats = []string{"yaml", "json"}
ValidExportFormats contains valid export output formats.
var ValidHTTPMethods = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"}
ValidHTTPMethods contains the valid HTTP methods.
var ValidIncidentImpacts = []string{"none", "minor", "major", "critical"}
ValidIncidentImpacts contains the valid incident impact levels.
var ValidIncidentStatuses = []string{"investigating", "identified", "monitoring", "resolved"}
ValidIncidentStatuses contains the valid incident statuses.
var ValidKeywordCheckTypes = []string{"contains", "not_contains"}
ValidKeywordCheckTypes contains the valid keyword check types.
var ValidMuteAlertTypes = []string{"status_down", "ssl_expiry", "ssl_invalid", "slow_response", "domain_expiry", "dns_record_missing", "dns_record_mismatch", "security_headers", "cert_transparency"}
ValidMuteAlertTypes contains the valid alert types for mutes.
var ValidMuteScopes = []string{"organization", "probe", "channel", "alert_type"}
ValidMuteScopes contains the valid mute scopes.
var ValidOutputFormats = []string{"table", "json", "yaml", "wide"}
ValidOutputFormats contains the valid output formats.
var ValidPagerDutySeverities = []string{"critical", "error", "warning", "info"}
ValidPagerDutySeverities contains valid PagerDuty severity levels.
var ValidPeriods = []string{"24h", "7d", "30d"}
ValidPeriods contains the valid time periods for stats.
var ValidProbeStatusFilters = []string{"up", "down", "degraded", "paused", "pending"}
ValidProbeStatusFilters contains the valid probe status filter values.
var ValidProbeStatuses = []string{"success", "failure"}
ValidProbeStatuses contains the valid probe result statuses.
var ValidSeverities = []string{"critical", "warning", "info"}
ValidSeverities contains the valid alert severity levels.
var ValidTeamRoles = []string{"owner", "admin", "member", "viewer"}
ValidTeamRoles contains the valid team member roles.
var ValidThemes = []string{"light", "dark", "system"}
ValidThemes contains the valid status page themes.
var ValidWebhookMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE"}
ValidWebhookMethods contains valid HTTP methods for webhooks.
Functions ¶
func ExitCodeName ¶
ExitCodeName returns a human-readable name for an exit code. Useful for logging and debugging.
func GetSuggestion ¶
GetSuggestion returns a suggestion for the given error type. Returns empty string if no suggestion is available.
func GetUserFriendlyMessage ¶
GetUserFriendlyMessage returns a user-friendly message for an API error code. Falls back to the provided default if no mapping exists.
func HandleError ¶
HandleError processes an error, prints a user-friendly message to stderr, and returns the appropriate exit code.
If err is nil, returns ExitSuccess (0).
The function handles these error types:
- *client.APIError: Maps API errors to appropriate exit codes and messages
- Network errors: Connection refused, DNS failures, timeouts
- Context errors: Deadline exceeded, canceled
- Generic errors: Returns ExitError with the error message
func InvalidValueError ¶
InvalidValueError formats an error message for an invalid value with an optional suggestion. This provides a consistent format across all CLI commands.
Example output:
Invalid value "htpp" for --check-type: must be one of: http, ping, tcp, dns_resolve Did you mean "http"?
func InvalidValueWithHintError ¶
InvalidValueWithHintError formats an error for an invalid value with a custom hint. Use this when the valid options are too numerous to list or when a custom message is better.
Example output:
Invalid value "abc" for --interval: must be a number between 30 and 3600
func RequiredArgError ¶
RequiredArgError returns a consistent error for missing required arguments.
func RequiredFlagError ¶
RequiredFlagError returns a consistent error for missing required flags. The format matches Cobra's built-in required flag errors for consistency.
func SetErrWriter ¶
SetErrWriter sets the writer for error output. Used for testing. Also reinitializes the formatter to use the new writer with colors disabled, ensuring test output contains plain text for assertion matching.
func SuggestFromOptions ¶
SuggestFromOptions returns the closest match from valid options for a given input. Returns an empty string if no close match is found (distance > maxDistance) or if the input exactly matches one of the options (case-insensitive). The maxDistance parameter controls how different the input can be from a valid option.
Types ¶
type ErrorFormatter ¶
type ErrorFormatter struct {
// contains filtered or unexported fields
}
ErrorFormatter provides color-coded error message formatting for CLI output. It uses the SDK's ColorManager to handle color mode preferences (auto/always/never) and respects NO_COLOR, TERM=dumb, and piped output detection.
Usage:
f := NewErrorFormatter()
f.PrintError("probe not found")
f.PrintContext("Probe ID", "abc123")
f.PrintSuggestion("Run 'stackeye probe list' to see available probes")
f.PrintRequestID("req_xyz789")
func NewErrorFormatter ¶
func NewErrorFormatter() *ErrorFormatter
NewErrorFormatter creates an ErrorFormatter using the CLI's configured color mode and writing to stderr.
func NewErrorFormatterWithColorManager ¶
func NewErrorFormatterWithColorManager(cm *sdkoutput.ColorManager, w io.Writer) *ErrorFormatter
NewErrorFormatterWithColorManager creates an ErrorFormatter with a custom ColorManager and writer. This is useful for testing with specific color modes.
func NewErrorFormatterWithWriter ¶
func NewErrorFormatterWithWriter(w io.Writer) *ErrorFormatter
NewErrorFormatterWithWriter creates an ErrorFormatter with a custom writer. This is useful for testing or redirecting error output.
func (*ErrorFormatter) FormatError ¶
func (f *ErrorFormatter) FormatError(msg string) string
FormatError returns a formatted error string with red "Error:" prefix. Use PrintError for direct output; use FormatError when building strings.
func (*ErrorFormatter) FormatInfo ¶
func (f *ErrorFormatter) FormatInfo(msg string) string
FormatInfo returns a formatted info string with cyan "Info:" prefix.
func (*ErrorFormatter) FormatSuccess ¶
func (f *ErrorFormatter) FormatSuccess(msg string) string
FormatSuccess returns a formatted success string with green "Success:" prefix.
func (*ErrorFormatter) FormatWarning ¶
func (f *ErrorFormatter) FormatWarning(msg string) string
FormatWarning returns a formatted warning string with yellow "Warning:" prefix.
func (*ErrorFormatter) PrintContext ¶
func (f *ErrorFormatter) PrintContext(key, value string)
PrintContext prints a key-value context pair indented under the error. Format: " <key>: <value>\n"
func (*ErrorFormatter) PrintError ¶
func (f *ErrorFormatter) PrintError(msg string)
PrintError prints an error message with red "Error:" prefix. Format: "Error: <message>\n"
func (*ErrorFormatter) PrintHint ¶
func (f *ErrorFormatter) PrintHint(hint string)
PrintHint prints a hint message indented under the error. Format: " <hint>\n"
func (*ErrorFormatter) PrintRequestID ¶
func (f *ErrorFormatter) PrintRequestID(requestID string)
PrintRequestID prints a request ID for support ticket reference. Format: " Request ID: <id> (include this when contacting support)\n"
func (*ErrorFormatter) PrintSuggestion ¶
func (f *ErrorFormatter) PrintSuggestion(text string)
PrintSuggestion prints a suggestion with a dimmed "Suggestion:" prefix. Format: " Suggestion: <text>\n"
func (*ErrorFormatter) PrintValidationErrors ¶
func (f *ErrorFormatter) PrintValidationErrors(fields map[string]string)
PrintValidationErrors prints a list of field validation errors. Format:
<field>: <message> <field>: <message>
func (*ErrorFormatter) PrintWarning ¶
func (f *ErrorFormatter) PrintWarning(msg string)
PrintWarning prints a warning message with yellow "Warning:" prefix. Format: "Warning: <message>\n"
type ErrorWithContext ¶
type ErrorWithContext struct {
Message string
Context map[string]string
Hint string
RequestID string
}
ErrorWithContext holds structured error information for formatted output.
func (*ErrorWithContext) Print ¶
func (e *ErrorWithContext) Print(f *ErrorFormatter)
Print outputs the error using the provided formatter.
type Suggestion ¶
Suggestion represents a suggested correction for a misspelled value.