errors

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2025 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package errors provides enterprise-grade error handling with stack traces, error codes, and categorization.

Index

Constants

View Source
const (
	CodeUnknown                = "UNKNOWN"
	CodeInvalidInput           = "INVALID_INPUT"
	CodeMissingField           = "MISSING_FIELD"
	CodeInvalidFormat          = "INVALID_FORMAT"
	CodeResourceNotFound       = "RESOURCE_NOT_FOUND"
	CodeUserNotFound           = "USER_NOT_FOUND"
	CodeTenantNotFound         = "TENANT_NOT_FOUND"
	CodeUnauthorized           = "UNAUTHORIZED"
	CodeInvalidCredentials     = "INVALID_CREDENTIALS"
	CodeTokenExpired           = "TOKEN_EXPIRED"
	CodeTokenInvalid           = "TOKEN_INVALID"
	CodeForbidden              = "FORBIDDEN"
	CodeInsufficientPrivileges = "INSUFFICIENT_PRIVILEGES"
	CodeResourceConflict       = "RESOURCE_CONFLICT"
	CodeDuplicateResource      = "DUPLICATE_RESOURCE"
	CodeInternalError          = "INTERNAL_ERROR"
	CodeDatabaseError          = "DATABASE_ERROR"
	CodeExternalServiceError   = "EXTERNAL_SERVICE_ERROR"
	CodeTimeout                = "TIMEOUT"
	CodeRateLimitExceeded      = "RATE_LIMIT_EXCEEDED"
	CodeCircuitBreakerOpen     = "CIRCUIT_BREAKER_OPEN"
	CodeServiceUnavailable     = "SERVICE_UNAVAILABLE"
	CodeConfigurationError     = "CONFIGURATION_ERROR"
	CodeBusinessRuleViolation  = "BUSINESS_RULE_VIOLATION"
)

Common Error Codes

Variables

This section is empty.

Functions

func Handle

func Handle(err error)

Handle handles an error using the global error handler.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable checks if an error is retryable.

func SetGlobalErrorHandler

func SetGlobalErrorHandler(handler *ErrorHandler)

SetGlobalErrorHandler sets the global error handler.

Types

type Error

type Error struct {
	Code       string                 `json:"code"`
	Message    string                 `json:"message"`
	Details    string                 `json:"details,omitempty"`
	Timestamp  time.Time              `json:"timestamp"`
	StackTrace []string               `json:"stack_trace,omitempty"`
	Context    map[string]interface{} `json:"context,omitempty"`
	Cause      error                  `json:"cause,omitempty"`
	Type       ErrorType              `json:"type"`
	Severity   Severity               `json:"severity"`
	Retryable  bool                   `json:"retryable"`
	UserID     string                 `json:"user_id,omitempty"`
	TenantID   string                 `json:"tenant_id,omitempty"`
	RequestID  string                 `json:"request_id,omitempty"`
	Operation  string                 `json:"operation,omitempty"`
}

Error represents an enterprise error with additional context.

func FromStandardError

func FromStandardError(err error) *Error

FromStandardError converts a standard error to an enterprise error.

func New

func New(code, message string) *Error

New creates a new enterprise error.

func NewBusinessError

func NewBusinessError(code, message string) *Error

NewBusinessError creates a business logic error.

func NewCircuitOpenError

func NewCircuitOpenError(code, message string) *Error

NewCircuitOpenError creates a circuit breaker open error.

func NewConflictError

func NewConflictError(code, message string) *Error

NewConflictError creates a conflict error.

func NewDependencyError

func NewDependencyError(code, message string) *Error

NewDependencyError creates a dependency error.

func NewForbiddenError

func NewForbiddenError(code, message string) *Error

NewForbiddenError creates a forbidden error.

func NewInternalError

func NewInternalError(code, message string) *Error

NewInternalError creates an internal server error.

func NewNotFoundError

func NewNotFoundError(code, message string) *Error

NewNotFoundError creates a not found error.

func NewRateLimitError

func NewRateLimitError(code, message string) *Error

NewRateLimitError creates a rate limit error.

func NewTimeoutError

func NewTimeoutError(code, message string) *Error

NewTimeoutError creates a timeout error.

func NewUnauthorizedError

func NewUnauthorizedError(code, message string) *Error

NewUnauthorizedError creates an unauthorized error.

func NewValidationError

func NewValidationError(code, message string) *Error

NewValidationError creates a validation error.

func NewWithType

func NewWithType(code, message string, errorType ErrorType) *Error

NewWithType creates a new error with specific type.

func Wrap

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

Wrap wraps an existing error with additional context.

func Wrapf

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

Wrapf wraps an 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 another error.

func (*Error) ToJSON

func (e *Error) ToJSON() ([]byte, error)

ToJSON converts the error to JSON.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause error.

func (*Error) WithContext

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

WithContext adds context to the error.

func (*Error) WithOperation

func (e *Error) WithOperation(operation string) *Error

WithOperation adds operation name to the error.

func (*Error) WithRequestID

func (e *Error) WithRequestID(requestID string) *Error

WithRequestID adds request ID to the error.

func (*Error) WithTenantID

func (e *Error) WithTenantID(tenantID string) *Error

WithTenantID adds tenant ID to the error.

func (*Error) WithUserID

func (e *Error) WithUserID(userID string) *Error

WithUserID adds user ID to the error.

type ErrorChain

type ErrorChain struct {
	Errors    []*Error  `json:"errors"`
	Root      *Error    `json:"root"`
	Timestamp time.Time `json:"timestamp"`
}

ErrorChain represents a chain of related errors.

func NewErrorChain

func NewErrorChain(root *Error) *ErrorChain

NewErrorChain creates a new error chain.

func (*ErrorChain) Add

func (ec *ErrorChain) Add(err *Error) *ErrorChain

Add adds an error to the chain.

func (*ErrorChain) Error

func (ec *ErrorChain) Error() string

Error implements the error interface.

func (*ErrorChain) Last

func (ec *ErrorChain) Last() *Error

Last returns the last error in the chain.

type ErrorCollection

type ErrorCollection struct {
	Errors    []*Error  `json:"errors"`
	Timestamp time.Time `json:"timestamp"`
}

ErrorCollection represents a collection of errors.

func NewErrorCollection

func NewErrorCollection() *ErrorCollection

NewErrorCollection creates a new error collection.

func (*ErrorCollection) Add

func (ec *ErrorCollection) Add(err *Error) *ErrorCollection

Add adds an error to the collection.

func (*ErrorCollection) Error

func (ec *ErrorCollection) Error() string

Error implements the error interface.

func (*ErrorCollection) HasErrors

func (ec *ErrorCollection) HasErrors() bool

HasErrors returns true if the collection has errors.

type ErrorHandler

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

ErrorHandler provides error handling utilities.

func NewErrorHandler

func NewErrorHandler(notifier ErrorNotifier) *ErrorHandler

NewErrorHandler creates a new error handler.

func (*ErrorHandler) Handle

func (eh *ErrorHandler) Handle(err error)

Handle handles an error with appropriate actions.

type ErrorNotifier

type ErrorNotifier interface {
	Notify(err *Error) error
}

ErrorNotifier defines the interface for error notification.

type ErrorType

type ErrorType string

ErrorType categorizes errors by their nature.

const (
	TypeValidation    ErrorType = "validation"
	TypeNotFound      ErrorType = "not_found"
	TypeUnauthorized  ErrorType = "unauthorized"
	TypeForbidden     ErrorType = "forbidden"
	TypeConflict      ErrorType = "conflict"
	TypeInternal      ErrorType = "internal"
	TypeExternal      ErrorType = "external"
	TypeTimeout       ErrorType = "timeout"
	TypeRateLimit     ErrorType = "rate_limit"
	TypeCircuitOpen   ErrorType = "circuit_open"
	TypeDependency    ErrorType = "dependency"
	TypeConfiguration ErrorType = "configuration"
	TypeBusiness      ErrorType = "business"
)

func GetErrorType

func GetErrorType(err error) ErrorType

GetErrorType returns the error type.

type HTTPErrorMapper

type HTTPErrorMapper struct{}

HTTPErrorMapper maps enterprise errors to HTTP status codes.

func (*HTTPErrorMapper) MapToHTTPResponse

func (m *HTTPErrorMapper) MapToHTTPResponse(err error) map[string]interface{}

MapToHTTPResponse maps an enterprise error to HTTP response body.

func (*HTTPErrorMapper) MapToHTTPStatus

func (m *HTTPErrorMapper) MapToHTTPStatus(err error) int

MapToHTTPStatus maps an enterprise error to HTTP status code.

type Severity

type Severity string

Severity indicates the severity level of an error.

const (
	SeverityLow      Severity = "low"
	SeverityMedium   Severity = "medium"
	SeverityHigh     Severity = "high"
	SeverityCritical Severity = "critical"
)

func GetSeverity

func GetSeverity(err error) Severity

GetSeverity returns the error severity.

Jump to

Keyboard shortcuts

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