errors

package
v0.2.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2026 License: MIT Imports: 13 Imported by: 0

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

View Source
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

View Source
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.

View Source
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.

View Source
var ValidAlertStatuses = []string{"active", "acknowledged", "resolved"}

ValidAlertStatuses contains the valid alert statuses.

View Source
var ValidBoolStrings = []string{"true", "false"}

ValidBoolStrings contains valid boolean string values.

View Source
var ValidChannelTypes = []string{"email", "slack", "webhook", "pagerduty", "discord", "teams", "sms"}

ValidChannelTypes contains the valid notification channel types.

View Source
var ValidCheckTypes = []string{"http", "ping", "tcp", "dns_resolve"}

ValidCheckTypes contains the valid probe check types.

View Source
var ValidDependencyDirections = []string{"parents", "children", "both"}

ValidDependencyDirections contains the valid probe dependency clear directions.

View Source
var ValidExportFormats = []string{"yaml", "json"}

ValidExportFormats contains valid export output formats.

View Source
var ValidHTTPMethods = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"}

ValidHTTPMethods contains the valid HTTP methods.

View Source
var ValidIncidentImpacts = []string{"none", "minor", "major", "critical"}

ValidIncidentImpacts contains the valid incident impact levels.

View Source
var ValidIncidentStatuses = []string{"investigating", "identified", "monitoring", "resolved"}

ValidIncidentStatuses contains the valid incident statuses.

View Source
var ValidKeywordCheckTypes = []string{"contains", "not_contains"}

ValidKeywordCheckTypes contains the valid keyword check types.

View Source
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.

View Source
var ValidMuteScopes = []string{"organization", "probe", "channel", "alert_type"}

ValidMuteScopes contains the valid mute scopes.

View Source
var ValidOutputFormats = []string{"table", "json", "yaml", "wide"}

ValidOutputFormats contains the valid output formats.

View Source
var ValidPagerDutySeverities = []string{"critical", "error", "warning", "info"}

ValidPagerDutySeverities contains valid PagerDuty severity levels.

View Source
var ValidPeriods = []string{"24h", "7d", "30d"}

ValidPeriods contains the valid time periods for stats.

View Source
var ValidProbeStatusFilters = []string{"up", "down", "degraded", "paused", "pending"}

ValidProbeStatusFilters contains the valid probe status filter values.

View Source
var ValidProbeStatuses = []string{"success", "failure"}

ValidProbeStatuses contains the valid probe result statuses.

View Source
var ValidSeverities = []string{"critical", "warning", "info"}

ValidSeverities contains the valid alert severity levels.

View Source
var ValidTeamRoles = []string{"owner", "admin", "member", "viewer"}

ValidTeamRoles contains the valid team member roles.

View Source
var ValidThemes = []string{"light", "dark", "system"}

ValidThemes contains the valid status page themes.

View Source
var ValidWebhookMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE"}

ValidWebhookMethods contains valid HTTP methods for webhooks.

Functions

func ExitCodeName

func ExitCodeName(code int) string

ExitCodeName returns a human-readable name for an exit code. Useful for logging and debugging.

func GetSuggestion

func GetSuggestion(errorType string) string

GetSuggestion returns a suggestion for the given error type. Returns empty string if no suggestion is available.

func GetUserFriendlyMessage

func GetUserFriendlyMessage(errorCode string, defaultMsg string) string

GetUserFriendlyMessage returns a user-friendly message for an API error code. Falls back to the provided default if no mapping exists.

func HandleError

func HandleError(err error) int

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

func InvalidValueError(flagName, value string, validOptions []string) error

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

func InvalidValueWithHintError(flagName, value, hint string) error

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

func RequiredArgError(argName string) error

RequiredArgError returns a consistent error for missing required arguments.

func RequiredFlagError

func RequiredFlagError(flagName string) error

RequiredFlagError returns a consistent error for missing required flags. The format matches Cobra's built-in required flag errors for consistency.

func SetErrWriter

func SetErrWriter(w io.Writer)

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

func SuggestFromOptions(input string, validOptions []string, maxDistance int) string

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

type Suggestion struct {
	Value    string
	Distance int
}

Suggestion represents a suggested correction for a misspelled value.

Jump to

Keyboard shortcuts

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