errors

package
v3.18.0 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2026 License: MIT Imports: 8 Imported by: 0

README

Error Handling Package

This package provides standardized error handling for the Buildkite CLI. It handles different types of errors consistently, provides helpful error messages and suggestions to users, and ensures a unified approach to error reporting across the application.

Features

  • Categorized Errors: Different error types (validation, API, not found, etc.) with specific handling
  • Contextual Error Messages: Errors include context about what operation failed
  • Helpful Suggestions: Error messages include suggestions on how to fix the issue
  • Command Integration: Easy integration with Kong commands
  • API Error Handling: Specialized handling for API errors with status code interpretation
  • Exit Codes: Appropriate exit codes for different error types

Usage

Creating Errors
import (
    bkErrors "github.com/buildkite/cli/v3/internal/errors"
)

// Create various types of errors
validationErr := bkErrors.NewValidationError(
    err, // Original error (can be nil)
    "Invalid input", // Details about the error
    "Try using a different value", // Suggestions (optional)
    "Check the documentation for valid options" // More suggestions
)

apiErr := bkErrors.NewAPIError(err, "API request failed")

notFoundErr := bkErrors.NewResourceNotFoundError(err, "Resource not found")
Adding Context to Errors
// Add suggestions to an existing error
err = bkErrors.WithSuggestions(err,
    "Try this instead",
    "Or try this other option"
)

// Add details to an existing error
err = bkErrors.WithDetails(err, "Additional context")
Checking Error Types
if bkErrors.IsNotFound(err) {
    // Handle not found error
}

if bkErrors.IsValidationError(err) {
    // Handle validation error
}

if bkErrors.IsAPIError(err) {
    // Handle API error
}
Wrapping API Errors
// Wrap HTTP errors with appropriate context
err = bkErrors.WrapAPIError(err, "fetching pipeline")
Command Integration
// Wrap a command's RunE function with standard error handling
cmd := &cobra.Command{
    RunE: bkErrors.WrapRunE(func(cmd *cobra.Command, args []string) error {
        // Command implementation
        return err
    }),
}
Using the Error Handler
// Create an error handler
handler := bkErrors.NewHandler().
    WithVerbose(verbose).
    WithWriter(os.Stderr)

// Handle an error
handler.Handle(err)

// Handle an error with operation context
handler.HandleWithDetails(err, "creating resource")

// Print a warning
handler.PrintWarning("Something might be wrong: %s", details)
Using the Command Error Handler
// In main.go:
func main() {
    rootCmd, _ := root.NewCmdRoot(f)

    // Execute with error handling
    bkErrors.ExecuteWithErrorHandling(rootCmd, verbose)
}

Documentation

Index

Constants

View Source
const (
	ExitCodeSuccess          = 0
	ExitCodeGenericError     = 1
	ExitCodeValidationError  = 2
	ExitCodeAPIError         = 3
	ExitCodeNotFoundError    = 4
	ExitCodePermissionError  = 5
	ExitCodeConfigError      = 6
	ExitCodeAuthError        = 7
	ExitCodeInternalError    = 8
	ExitCodeUserAbortedError = 130 // Same as Ctrl+C in bash
)

Exit codes for different error types

Variables

View Source
var (
	// ErrConfiguration indicates an error in the user's configuration
	ErrConfiguration = errors.New("configuration error")

	// ErrValidation indicates invalid input from the user
	ErrValidation = errors.New("validation error")

	// ErrAPI indicates an error from the Buildkite API
	ErrAPI = errors.New("API error")

	// ErrResourceNotFound indicates a requested resource was not found
	ErrResourceNotFound = errors.New("resource not found")

	// ErrPermissionDenied indicates the user lacks permission
	ErrPermissionDenied = errors.New("permission denied")

	// ErrAuthentication indicates an issue with authentication
	ErrAuthentication = errors.New("authentication error")

	// ErrInternal indicates an internal error in the CLI
	ErrInternal = errors.New("internal error")

	// ErrUserAborted indicates the user has canceled an operation
	ErrUserAborted = errors.New("user aborted")
)

Standard error types that can be used to categorize errors

Functions

func GetExitCodeForError

func GetExitCodeForError(err error) int

GetExitCodeForError returns the exit code for a given error

func IsAPIError

func IsAPIError(err error) bool

IsAPIError returns true if the error indicates an API failure

func IsAuthenticationError

func IsAuthenticationError(err error) bool

IsAuthenticationError returns true if the error indicates an authentication failure

func IsConfigurationError

func IsConfigurationError(err error) bool

IsConfigurationError returns true if the error indicates a configuration issue

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns true if the error indicates a resource was not found

func IsPermissionDeniedError

func IsPermissionDeniedError(err error) bool

IsPermissionDeniedError returns true if the error indicates a permission issue

func IsUserAborted

func IsUserAborted(err error) bool

IsUserAborted returns true if the error indicates the user aborted the operation

func IsValidationError

func IsValidationError(err error) bool

IsValidationError returns true if the error indicates a validation failure

func MessageForError

func MessageForError(err error) string

MessageForError returns a formatted message for an error without exiting

func NewAPIError

func NewAPIError(err error, details string, suggestions ...string) error

NewAPIError creates a new API error

func NewAuthenticationError

func NewAuthenticationError(err error, details string, suggestions ...string) error

NewAuthenticationError creates a new authentication error

func NewConfigurationError

func NewConfigurationError(err error, details string, suggestions ...string) error

NewConfigurationError creates a new configuration error

func NewInternalError

func NewInternalError(err error, details string, suggestions ...string) error

NewInternalError creates a new internal error

func NewPermissionDeniedError

func NewPermissionDeniedError(err error, details string, suggestions ...string) error

NewPermissionDeniedError creates a new permission denied error

func NewResourceNotFoundError

func NewResourceNotFoundError(err error, details string, suggestions ...string) error

NewResourceNotFoundError creates a new resource not found error

func NewUserAbortedError

func NewUserAbortedError(err error, details string, suggestions ...string) error

NewUserAbortedError creates a new user aborted error

func NewValidationError

func NewValidationError(err error, details string, suggestions ...string) error

NewValidationError creates a new validation error

func WithDetails

func WithDetails(err error, details string) error

WithDetails adds details to an existing error

func WithSuggestions

func WithSuggestions(err error, suggestions ...string) error

WithSuggestions adds suggestions to an existing error

func WrapAPIError

func WrapAPIError(err error, operation string) error

WrapAPIError wraps an API error with appropriate context and suggestions

Types

type APIErrorResponse

type APIErrorResponse struct {
	Message string            `json:"message"`
	Errors  []string          `json:"errors,omitempty"`
	Details map[string]string `json:"details,omitempty"`
}

APIErrorResponse represents a Buildkite API error response

type Error

type Error struct {
	// Original is the underlying error
	Original error

	// Category is the broad category of the error
	Category error

	// Details contains additional detail about the error
	Details string

	// Suggestions provides hints on how to fix the error
	Suggestions []string
}

Error represents a CLI error with context

func NewError

func NewError(original error, category error, details string, suggestions ...string) *Error

NewError creates a new Error with the given attributes

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface

func (*Error) FormattedError

func (e *Error) FormattedError() string

FormattedError returns a formatted multi-line error message suitable for display

func (*Error) Is

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

Is implements the errors.Is interface to allow checking error types

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap implements the errors.Unwrap interface to allow using errors.Is and errors.As

type Handler

type Handler struct {
	// Writer is where error messages will be written
	Writer io.Writer
	// ExitFunc is the function called to exit the program with a specific code
	ExitFunc func(int)
	// Verbose enables more detailed error messages
	Verbose bool
}

Handler processes errors from commands and formats them appropriately

func NewHandler

func NewHandler() *Handler

NewHandler creates a new Handler with default settings

func (*Handler) Handle

func (h *Handler) Handle(err error)

Handle processes an error and outputs it appropriately

func (*Handler) HandleWithDetails

func (h *Handler) HandleWithDetails(err error, operation string)

HandleWithDetails processes an error with additional contextual details

func (*Handler) PrintWarning

func (h *Handler) PrintWarning(format string, args ...interface{})

PrintWarning prints a warning message

func (*Handler) WithExitFunc

func (h *Handler) WithExitFunc(f func(int)) *Handler

WithExitFunc sets the exit function

func (*Handler) WithVerbose

func (h *Handler) WithVerbose(v bool) *Handler

WithVerbose sets the verbose flag

func (*Handler) WithWriter

func (h *Handler) WithWriter(w io.Writer) *Handler

WithWriter sets the writer for error output

Jump to

Keyboard shortcuts

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