Documentation
¶
Overview ¶
Package errors provides structured error types with automatic stack traces. It wraps cockroachdb/errors to provide enterprise-grade error handling with typed sentinels, IsRetryable() interface, and structured error context.
Key features:
- Automatic stack trace capture for all errors
- Typed error sentinels for type-safe error detection
- IsRetryable() interface for intelligent retry logic
- Structured error context (HTTP status codes, validation fields, etc.)
- Safe error details for production logging
Index ¶
- Variables
- func ExtractErrorInfo(err error) map[string]any
- func FormatError(err error) string
- func GetHTTPStatusCode(err error) int
- func GetSafeDetails(err error) string
- func GetStackTrace(err error) string
- func GetStackTraceLines(err error) []string
- func HasStackTrace(err error) bool
- func IsContextError(err error) bool
- func IsNetworkError(err error) bool
- func IsNotFound(err error) bool
- func IsPermanentError(err error) bool
- func IsRetryable(err error) bool
- func IsRetryableTimeout(err error) bool
- func IsTimeout(err error) bool
- func IsTransientError(err error) bool
- func IsValidation(err error) bool
- func NewCircuitBreakerError(message, operation, state string, opts ...Option) error
- func NewHTTPError(statusCode int, message string, cause error) error
- func NewInternalError(message string, cause error) error
- func NewNetworkError(message, operation string, opts ...Option) error
- func NewNotFoundError(message string, cause error) error
- func NewProcessingError(message, operation string, opts ...Option) error
- func NewRateLimitError(message, operation string, retryAfter time.Duration, opts ...Option) error
- func NewRetryableError(message, operation string, retryAfter time.Duration, opts ...Option) error
- func NewRetryableProcessingError(message, operation string, opts ...Option) error
- func NewTimeoutError(message, operation string, duration time.Duration, opts ...Option) error
- func NewValidationError(message, field string, opts ...Option) error
- type CircuitBreakerError
- type HTTPError
- type NetworkError
- type Option
- func WithCause(cause error) Option
- func WithComponent(component string) Option
- func WithField(field string) Option
- func WithItemID(itemID string) Option
- func WithMessage(message string) Option
- func WithOperation(operation string) Option
- func WithRetryable(retryable bool) Option
- func WithState(state string) Option
- func WithStatusCode(statusCode int) Option
- func WithTransient(transient bool) Option
- func WithValue(value any) Option
- type ProcessingError
- type RateLimitError
- type Retryable
- type RetryableError
- type TimeoutError
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
var ( // New creates a new error with a stack trace. New = errors.New // Errorf creates a new error with formatted message and stack trace. Errorf = errors.Errorf // Wrap annotates an error with a message and stack trace. Wrap = errors.Wrap // Wrapf annotates an error with a formatted message and stack trace. Wrapf = errors.Wrapf // WithStack adds a stack trace to an error if it doesn't have one. WithStack = errors.WithStack // Is checks if an error matches a target using error chain traversal. Is = errors.Is // As finds the first error in the chain that matches target type. As = errors.As // Unwrap returns the result of calling Unwrap on err, if err's type contains // an Unwrap method returning error. Otherwise, Unwrap returns nil. Unwrap = errors.Unwrap // Cause returns the underlying cause of the error, if possible. Cause = errors.Cause )
Re-export commonly used cockroachdb/errors functions. These automatically include stack traces when creating or wrapping errors.
var ( // ErrRateLimited indicates API rate limiting. ErrRateLimited = errors.New("rate limited") // ErrNetworkTimeout indicates network timeout. ErrNetworkTimeout = errors.New("network timeout") // ErrServerError indicates 5xx HTTP server error. ErrServerError = errors.New("server error") // ErrConnectionError indicates network connection failure. ErrConnectionError = errors.New("connection error") // ErrDeadlock indicates database deadlock. ErrDeadlock = errors.New("database deadlock") // ErrCircuitOpen indicates circuit breaker is open. ErrCircuitOpen = errors.New("circuit breaker open") // ErrInvalidResponse indicates malformed or unexpected response. ErrInvalidResponse = errors.New("invalid response") )
Sentinel errors for common retryable conditions. Use these when wrapping errors to enable type-safe error detection.
var ( // ErrActivityNotFound indicates a requested activity was not found. ErrActivityNotFound = errors.New("activity not found") // ErrLocationNotFound indicates a requested location was not found. ErrLocationNotFound = errors.New("location not found") )
Sentinel errors for common API/backend error conditions.
Functions ¶
func ExtractErrorInfo ¶
ExtractErrorInfo returns structured information about the error. Returns a map with error type, retryability, and extracted fields.
Example:
info := ExtractErrorInfo(err)
// info = map[string]any{
// "type": "HTTPError",
// "retryable": true,
// "status_code": 503,
// "message": "Service Unavailable",
// }
func FormatError ¶
FormatError returns a formatted error string with type information. Useful for structured logging and debugging.
Example output:
HTTPError(500): Internal Server Error: database connection failed
func GetHTTPStatusCode ¶
GetHTTPStatusCode extracts HTTP status code from error, or 0 if not found.
func GetSafeDetails ¶
GetSafeDetails returns error details safe for production logging. Redacts sensitive information while preserving debugging context.
Example:
err := NewHTTPError(500, "Internal Server Error", fmt.Errorf("db password: secret123"))
safe := GetSafeDetails(err)
// safe contains error type and structure, but sensitive data is redacted
func GetStackTrace ¶
GetStackTrace returns a formatted stack trace for the error. Returns empty string if the error has no stack trace.
Example output:
main.processItem
/path/to/main.go:42
main.worker
/path/to/main.go:28
main.main
/path/to/main.go:15
func GetStackTraceLines ¶
GetStackTraceLines returns the stack trace as individual lines. Returns empty slice if the error has no stack trace.
func HasStackTrace ¶
HasStackTrace checks if the error has a stack trace.
func IsContextError ¶
IsContextError checks if err is a context error (DeadlineExceeded or Canceled).
func IsNetworkError ¶
IsNetworkError checks if err is a network error (NetworkError or net.Error).
func IsNotFound ¶ added in v1.0.7
IsNotFound checks if an error represents a "not found" condition. Returns true for: - ErrActivityNotFound or ErrLocationNotFound sentinels - Any error wrapping these sentinels - HTTPError with status code 404
func IsPermanentError ¶
IsPermanentError checks if err represents a permanent failure. Permanent failures should not be retried. Examples: validation errors, authentication errors, not found errors.
func IsRetryable ¶
IsRetryable checks if an error should trigger a retry. It checks in priority order: 1. Context errors (DeadlineExceeded, Canceled) - NOT retryable 2. Any error implementing Retryable interface (generic check) 3. Typed sentinel errors (ErrRateLimited, ErrNetworkTimeout, etc.) 4. HTTPError with retryable status codes (429, 5xx) 5. Defensive fallback for untyped rate limit messages
CRITICAL: Context errors are checked FIRST because some error types implement IsRetryable() but may wrap context errors. If context.DeadlineExceeded is wrapped, retrying with the same context will fail immediately - these operations should be abandoned, not retried.
The generic Retryable interface check (step 2) works with error types from any package, not just go-errors. External packages can define their own error types with IsRetryable() methods, and they will be properly detected.
Example usage:
if err != nil {
if IsRetryable(err) {
// Use exponential backoff
time.Sleep(backoff)
continue
}
return err // Permanent failure
}
func IsRetryableTimeout ¶
IsRetryableTimeout checks if err is a retryable timeout. Returns false for context.DeadlineExceeded (parent context expired). Returns true for other timeout errors (network timeouts, API timeouts, etc.).
func IsTimeout ¶
IsTimeout checks if err is a timeout error (TimeoutError or net.Error with Timeout()).
func IsTransientError ¶
IsTransientError checks if err represents a transient failure. Transient failures are temporary and should be retried. Examples: network errors, rate limits, server errors.
func IsValidation ¶
IsValidation checks if err is a ValidationError.
func NewCircuitBreakerError ¶
NewCircuitBreakerError creates a CircuitBreakerError with automatic stack trace.
func NewHTTPError ¶
NewHTTPError creates an HTTPError with automatic stack trace.
func NewInternalError ¶ added in v1.0.6
NewInternalError creates an HTTPError with status 500 (Internal Server Error). This is a convenience wrapper for API/backend services.
func NewNetworkError ¶
NewNetworkError creates a NetworkError with automatic stack trace.
func NewNotFoundError ¶ added in v1.0.8
NewNotFoundError creates an HTTPError with status 404 (Not Found). This is a convenience wrapper for API/backend services.
func NewProcessingError ¶
NewProcessingError creates a ProcessingError with automatic stack trace.
func NewRateLimitError ¶
NewRateLimitError creates a RateLimitError with automatic stack trace.
func NewRetryableError ¶ added in v1.0.3
NewRetryableError creates a RetryableError with automatic stack trace.
func NewRetryableProcessingError ¶
NewRetryableProcessingError creates a retryable ProcessingError with automatic stack trace.
func NewTimeoutError ¶
NewTimeoutError creates a TimeoutError with automatic stack trace.
func NewValidationError ¶
NewValidationError creates a ValidationError with automatic stack trace.
Types ¶
type CircuitBreakerError ¶
type CircuitBreakerError struct {
Message string
Operation string
Component string
State string
Err error
}
CircuitBreakerError represents circuit breaker protection. Automatically includes stack trace from creation point.
func (*CircuitBreakerError) Error ¶
func (e *CircuitBreakerError) Error() string
func (*CircuitBreakerError) IsRetryable ¶
func (e *CircuitBreakerError) IsRetryable() bool
func (*CircuitBreakerError) Unwrap ¶
func (e *CircuitBreakerError) Unwrap() error
type HTTPError ¶
HTTPError wraps HTTP-related errors with status code information. Automatically includes stack trace from creation point.
func IsHTTPError ¶
IsHTTPError checks if err is an HTTPError and returns it.
func (*HTTPError) IsRetryable ¶
IsRetryable returns true for 5xx errors and 429 (rate limit).
type NetworkError ¶
type NetworkError struct {
Message string
Operation string
Component string
IsTransient bool
Err error
}
NetworkError represents a network connectivity failure. Automatically includes stack trace from creation point.
func (*NetworkError) Error ¶
func (e *NetworkError) Error() string
func (*NetworkError) IsRetryable ¶
func (e *NetworkError) IsRetryable() bool
func (*NetworkError) Unwrap ¶
func (e *NetworkError) Unwrap() error
type Option ¶
type Option func(any)
Option is a functional option for configuring error creation. Use with error constructor functions to specify optional fields.
Example:
err := NewProcessingError("Failed to process item", "ProcessItem",
WithCause(dbErr),
WithItemID("item-123"),
WithRetryable(true))
func WithCause ¶
WithCause sets the underlying cause for an error. Use this to wrap lower-level errors while maintaining the error chain.
Example:
dbErr := db.Query(...)
err := NewProcessingError("Failed to load user", "LoadUser",
WithCause(dbErr))
func WithComponent ¶ added in v1.0.1
WithComponent sets the component name for an error. Component identifies where the error occurred (e.g., "enricher", "curator", "llm_matcher"). Applies to all error types that have a Component field.
Example:
err := NewProcessingError("Failed to enrich activity", "EnrichActivity",
WithComponent("enricher"),
WithItemID(activity.ID))
func WithField ¶
WithField sets the field name for validation errors. Only applies to ValidationError types, ignored for others.
Example:
err := NewValidationError("Invalid format", "",
WithField("email"))
func WithItemID ¶
WithItemID sets the item ID for processing errors. Only applies to ProcessingError types, ignored for others.
Example:
err := NewProcessingError("Failed to process activity", "ProcessActivity",
WithItemID("activity-123"))
func WithMessage ¶
WithMessage sets the message for errors that support it. Applies to most error types.
Example:
err := NewHTTPError(500, "Internal Server Error", nil,
WithMessage("Database connection failed"))
func WithOperation ¶
WithOperation sets the operation name for errors that support it. Applies to TimeoutError, RateLimitError, ProcessingError, NetworkError, and CircuitBreakerError.
Example:
err := NewTimeoutError("API call timed out", "GetUser", 30*time.Second)
func WithRetryable ¶
WithRetryable sets whether a processing error is retryable. Only applies to ProcessingError types, ignored for others.
Example:
err := NewProcessingError("Database connection lost", "SaveData",
WithRetryable(true))
func WithState ¶
WithState sets the circuit breaker state. Only applies to CircuitBreakerError types, ignored for others.
Example:
err := NewCircuitBreakerError("Too many failures", "CallAPI", "",
WithState("open"))
func WithStatusCode ¶
WithStatusCode sets the HTTP status code. Only applies to HTTPError types, ignored for others.
Example:
err := NewHTTPError(0, "Server error", cause,
WithStatusCode(503))
func WithTransient ¶
WithTransient sets whether a network error is transient. Only applies to NetworkError types, ignored for others.
Example:
err := NewNetworkError("DNS lookup failed", "Connect",
WithTransient(false))
type ProcessingError ¶
type ProcessingError struct {
Message string
Operation string
ItemID string
Component string
Retryable bool
Err error
}
ProcessingError represents an error during data processing. Automatically includes stack trace from creation point.
func (*ProcessingError) Error ¶
func (e *ProcessingError) Error() string
func (*ProcessingError) IsRetryable ¶
func (e *ProcessingError) IsRetryable() bool
func (*ProcessingError) Unwrap ¶
func (e *ProcessingError) Unwrap() error
type RateLimitError ¶
type RateLimitError struct {
Message string
Operation string
Component string
RetryAfter time.Duration
Err error
}
RateLimitError represents rate limiting with retry-after duration. Automatically includes stack trace from creation point.
func (*RateLimitError) Error ¶
func (e *RateLimitError) Error() string
func (*RateLimitError) IsRetryable ¶
func (e *RateLimitError) IsRetryable() bool
func (*RateLimitError) Unwrap ¶
func (e *RateLimitError) Unwrap() error
type Retryable ¶
type Retryable interface {
IsRetryable() bool
}
Retryable interface defines errors that can be retried. Implement this interface on custom error types to enable intelligent retry logic without string parsing.
type RetryableError ¶ added in v1.0.3
type RetryableError struct {
Message string
Operation string
Component string
RetryAfter time.Duration
Err error
}
RetryableError represents a generic retryable error with retry-after duration. More general than RateLimitError - can be used for any temporary failure. Automatically includes stack trace from creation point.
func (*RetryableError) Error ¶ added in v1.0.3
func (e *RetryableError) Error() string
func (*RetryableError) IsRetryable ¶ added in v1.0.3
func (e *RetryableError) IsRetryable() bool
func (*RetryableError) Unwrap ¶ added in v1.0.3
func (e *RetryableError) Unwrap() error
type TimeoutError ¶
type TimeoutError struct {
Message string
Operation string
Component string
Duration time.Duration
Err error
}
TimeoutError represents an operation that exceeded its deadline. Automatically includes stack trace from creation point.
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
func (*TimeoutError) IsRetryable ¶
func (e *TimeoutError) IsRetryable() bool
func (*TimeoutError) Unwrap ¶
func (e *TimeoutError) Unwrap() error
type ValidationError ¶
ValidationError represents a data validation failure. Automatically includes stack trace from creation point.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
func (*ValidationError) IsRetryable ¶
func (e *ValidationError) IsRetryable() bool
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error