errors

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2025 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Copyright (c) 2025 Guilherme Silva Sousa Licensed under the MIT License See LICENSE file in the project root for full license information.

Copyright (c) 2025 Guilherme Silva Sousa Licensed under the MIT License See LICENSE file in the project root for full license information. Package errors provides comprehensive error handling for CCMD.

Copyright (c) 2025 Guilherme Silva Sousa Licensed under the MIT License See LICENSE file in the project root for full license information.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultHandler = NewHandler(nil)

DefaultHandler is the default error handler instance

Functions

func As

func As(err error, target interface{}) bool

As is a wrapper around errors.As for convenience

func Handle

func Handle(err error) bool

Handle is a convenience function using the default handler

func HandleFatal

func HandleFatal(err error)

HandleFatal is a convenience function using the default handler

func Is

func Is(err, target error) bool

Is is a wrapper around errors.Is for convenience

func IsAlreadyExists

func IsAlreadyExists(err error) bool

IsAlreadyExists checks if an error is an already exists error

func IsCode

func IsCode(err error, code ErrorCode) bool

IsCode checks if an error has a specific code

func IsGitError

func IsGitError(err error) bool

IsGitError checks if an error is git related

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError checks if an error is network related

func IsNotFound

func IsNotFound(err error) bool

IsNotFound checks if an error is a not found error

Example
package main

import (
	"fmt"

	"github.com/gifflet/ccmd/pkg/errors"
)

func main() {
	err1 := errors.New(errors.CodeNotFound, "not found")
	err2 := errors.New(errors.CodeCommandNotFound, "command not found")
	err3 := errors.New(errors.CodeInternal, "internal error")

	fmt.Println(errors.IsNotFound(err1)) // true
	fmt.Println(errors.IsNotFound(err2)) // true
	fmt.Println(errors.IsNotFound(err3)) // false
}
Output:
true
true
false

func IsPermissionDenied

func IsPermissionDenied(err error) bool

IsPermissionDenied checks if an error is a permission denied error

func IsValidationError

func IsValidationError(err error) bool

IsValidationError checks if an error is a validation error

func NewMulti

func NewMulti(errs ...error) error

NewMulti creates a new MultiError from a list of errors

func RecoverPanic

func RecoverPanic(name string)

RecoverPanic recovers from panics and converts them to errors

Types

type CommandRunner

type CommandRunner func(cmd *cobra.Command, args []string) error

CommandRunner wraps a cobra command with error handling

func WrapCommand

func WrapCommand(name string, runner CommandRunner) CommandRunner

WrapCommand wraps a command runner with error handling and logging

type Error

type Error struct {
	Code    ErrorCode
	Message string
	Details map[string]interface{}
	Cause   error
}

Error represents a structured error with code, message and context

Example (Basic)
package main

import (
	"fmt"

	"github.com/gifflet/ccmd/pkg/errors"
)

func main() {
	// Create a simple error
	err := errors.New(errors.CodeNotFound, "command not found")
	fmt.Println(err)
}
Output:
[NOT_FOUND] command not found
Example (WithDetails)
package main

import (
	"fmt"

	"github.com/gifflet/ccmd/pkg/errors"
)

func main() {
	// Create an error with details
	err := errors.New(errors.CodeConfigInvalid, "invalid configuration").
		WithDetail("file", "ccmd.yaml").
		WithDetail("line", 42)

	// The error includes the code and message
	fmt.Println(err)
}
Output:
[CONFIG_INVALID] invalid configuration

func New

func New(code ErrorCode, message string) *Error

New creates a new error with the given code and message

func Newf

func Newf(code ErrorCode, format string, args ...interface{}) *Error

Newf creates a new error with formatted message

func Wrap

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

Wrap wraps an existing error with additional context

Example
package main

import (
	"fmt"

	"github.com/gifflet/ccmd/pkg/errors"
)

func main() {
	// Simulate an underlying error
	originalErr := fmt.Errorf("connection timeout")

	// Wrap it with context
	err := errors.Wrap(originalErr, errors.CodeNetworkTimeout, "failed to fetch repository")

	fmt.Println(err)
}
Output:
[NETWORK_TIMEOUT] failed to fetch repository: connection timeout

func Wrapf

func Wrapf(err error, code ErrorCode, format string, args ...interface{}) *Error

Wrapf wraps an existing error with formatted message

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface

func (*Error) Is

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

Is checks if the error matches the target

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error

func (*Error) WithDetail

func (e *Error) WithDetail(key string, value interface{}) *Error

WithDetail adds a detail to the error

func (*Error) WithDetails

func (e *Error) WithDetails(details map[string]interface{}) *Error

WithDetails adds multiple details to the error

type ErrorCode

type ErrorCode string

ErrorCode represents a specific error type

const (
	// CodeUnknown represents an unknown error
	CodeUnknown ErrorCode = "UNKNOWN"
	// CodeInternal represents an internal error
	CodeInternal ErrorCode = "INTERNAL"
	// CodeInvalidArgument represents an invalid argument error
	CodeInvalidArgument ErrorCode = "INVALID_ARGUMENT"
	// CodeNotFound represents a not found error
	CodeNotFound ErrorCode = "NOT_FOUND"
	// CodeAlreadyExists represents an already exists error
	CodeAlreadyExists ErrorCode = "ALREADY_EXISTS"
	// CodePermissionDenied represents a permission denied error
	CodePermissionDenied ErrorCode = "PERMISSION_DENIED"

	// CodeGitClone represents a git clone error
	CodeGitClone ErrorCode = "GIT_CLONE"
	// CodeGitInvalidRepo represents an invalid git repository error
	CodeGitInvalidRepo ErrorCode = "GIT_INVALID_REPO"
	// CodeGitAuth represents a git authentication error
	CodeGitAuth ErrorCode = "GIT_AUTH"
	// CodeGitNotFound represents a git not found error
	CodeGitNotFound ErrorCode = "GIT_NOT_FOUND"

	// CodeCommandNotFound represents a command not found error
	CodeCommandNotFound ErrorCode = "COMMAND_NOT_FOUND"
	// CodeCommandExists represents a command already exists error
	CodeCommandExists ErrorCode = "COMMAND_EXISTS"
	// CodeCommandInvalid represents an invalid command error
	CodeCommandInvalid ErrorCode = "COMMAND_INVALID"
	// CodeCommandExecute represents a command execution error
	CodeCommandExecute ErrorCode = "COMMAND_EXECUTE"

	// CodeConfigInvalid represents an invalid configuration error
	CodeConfigInvalid ErrorCode = "CONFIG_INVALID"
	// CodeConfigNotFound represents a configuration not found error
	CodeConfigNotFound ErrorCode = "CONFIG_NOT_FOUND"
	// CodeConfigParse represents a configuration parse error
	CodeConfigParse ErrorCode = "CONFIG_PARSE"

	// CodeFileNotFound represents a file not found error
	CodeFileNotFound ErrorCode = "FILE_NOT_FOUND"
	// CodeFileExists represents a file already exists error
	CodeFileExists ErrorCode = "FILE_EXISTS"
	// CodeFilePermission represents a file permission error
	CodeFilePermission ErrorCode = "FILE_PERMISSION"
	// CodeFileIO represents a file I/O error
	CodeFileIO ErrorCode = "FILE_IO"

	// CodeValidationFailed represents a validation failure
	CodeValidationFailed ErrorCode = "VALIDATION_FAILED"
	// CodeValidationSchema represents a schema validation error
	CodeValidationSchema ErrorCode = "VALIDATION_SCHEMA"

	// CodeNetworkTimeout represents a network timeout error
	CodeNetworkTimeout ErrorCode = "NETWORK_TIMEOUT"
	// CodeNetworkUnavailable represents a network unavailable error
	CodeNetworkUnavailable ErrorCode = "NETWORK_UNAVAILABLE"

	// CodeValidation represents a general validation error
	CodeValidation ErrorCode = "VALIDATION"
	// CodeLockConflict represents a lock conflict error
	CodeLockConflict ErrorCode = "LOCK_CONFLICT"
	// CodeTimeout represents a general timeout error
	CodeTimeout ErrorCode = "TIMEOUT"
	// CodePartialFailure represents a partial failure where some operations succeeded
	CodePartialFailure ErrorCode = "PARTIAL_FAILURE"
	// CodeNotImplemented represents a not implemented error
	CodeNotImplemented ErrorCode = "NOT_IMPLEMENTED"
)

func GetCode

func GetCode(err error) ErrorCode

GetCode extracts the error code from an error

Example
package main

import (
	"fmt"

	"github.com/gifflet/ccmd/pkg/errors"
)

func main() {
	// Create different types of errors
	err1 := errors.New(errors.CodeNotFound, "not found")
	err2 := fmt.Errorf("standard error")

	// Get error codes
	fmt.Println(errors.GetCode(err1))
	fmt.Println(errors.GetCode(err2))
}
Output:
NOT_FOUND
UNKNOWN

type Handler

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

Handler provides centralized error handling with logging

Example
package main

import (
	"os"

	"github.com/gifflet/ccmd/pkg/errors"
	"github.com/gifflet/ccmd/pkg/logger"
)

func main() {
	// Set up a test logger
	log := logger.New(os.Stdout, logger.InfoLevel)
	handler := errors.NewHandler(log)

	// Create an error
	err := errors.New(errors.CodeCommandNotFound, "command 'test' not found").
		WithDetail("command", "test")

	// Handle the error (this would normally print to stderr)
	handler.Handle(err)
}

func NewHandler

func NewHandler(log logger.Logger) *Handler

NewHandler creates a new error handler

func (*Handler) Handle

func (h *Handler) Handle(err error) bool

Handle processes an error and returns true if it was handled

func (*Handler) HandleFatal

func (h *Handler) HandleFatal(err error)

HandleFatal processes a fatal error and exits

func (*Handler) SetOutputFuncs

func (h *Handler) SetOutputFuncs(printError, printWarning, printInfo OutputFunc)

SetOutputFuncs sets custom output functions

type MultiError

type MultiError struct {
	Errors []error
}

MultiError represents multiple errors

func (*MultiError) Error

func (e *MultiError) Error() string

Error implements the error interface

type OutputFunc

type OutputFunc func(format string, args ...interface{})

OutputFunc is a function that outputs messages to the user

Jump to

Keyboard shortcuts

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