errors

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package errors provides a structured error handling system with rich context. It includes error codes, HTTP/gRPC status mapping, validation helpers, and detail support. It is designed to be idiomatic and interoperate with standard library errors and google.golang.org/grpc/status.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FromGRPCError

func FromGRPCError(err error) error

FromGRPCError extracts our custom error from a gRPC status error

func GetGRPCCode

func GetGRPCCode(err error) codes.Code

GetGRPCCode extracts gRPC code from error, defaults to Unknown

func GetHTTPStatus

func GetHTTPStatus(err error) int

GetHTTPStatus extracts HTTP status from error, defaults to 500

func Is

func Is(err error, code Code) bool

Is checks if the error matches the target error code

Types

type Code

type Code string

Code represents an internal error code

const (
	// Validation errors
	CodeValidationFailed Code = "VALIDATION_FAILED"
	CodeInvalidArgument  Code = "INVALID_ARGUMENT"
	CodeMissingField     Code = "MISSING_FIELD"
	CodeInvalidFormat    Code = "INVALID_FORMAT"
	CodeOutOfRange       Code = "OUT_OF_RANGE"

	// Resource errors
	CodeNotFound      Code = "NOT_FOUND"
	CodeAlreadyExists Code = "ALREADY_EXISTS"
	CodeConflict      Code = "CONFLICT"
	CodeTaken         Code = "TAKEN"

	// Authentication/Authorization errors
	CodeUnauthenticated Code = "UNAUTHENTICATED"
	CodeUnauthorized    Code = "UNAUTHORIZED"
	CodeForbidden       Code = "FORBIDDEN"

	// System errors
	CodeInternalError      Code = "INTERNAL_ERROR"
	CodeServiceUnavailable Code = "SERVICE_UNAVAILABLE"
	CodeTimeout            Code = "TIMEOUT"
	CodeRateLimited        Code = "RATE_LIMITED"

	// Business logic errors
	CodeBusinessRuleViolation Code = "BUSINESS_RULE_VIOLATION"
	CodeOperationNotAllowed   Code = "OPERATION_NOT_ALLOWED"
	CodeResourceLocked        Code = "RESOURCE_LOCKED"

	// Rate limiting and capacity
	CodeQuotaExceeded    Code = "QUOTA_EXCEEDED"
	CodeCapacityExceeded Code = "CAPACITY_EXCEEDED"

	// Data integrity
	CodeDataCorruption   Code = "DATA_CORRUPTION"
	CodeChecksumMismatch Code = "CHECKSUM_MISMATCH"

	// Network and connectivity
	CodeNetworkError        Code = "NETWORK_ERROR"
	CodeConnectionFailed    Code = "CONNECTION_FAILED"
	CodeDNSResolutionFailed Code = "DNS_RESOLUTION_FAILED"

	// File and storage
	CodeFileNotFound      Code = "FILE_NOT_FOUND"
	CodeStorageError      Code = "STORAGE_ERROR"
	CodeInsufficientSpace Code = "INSUFFICIENT_SPACE"

	// Configuration and setup
	CodeConfigurationError Code = "CONFIGURATION_ERROR"
	CodeMissingDependency  Code = "MISSING_DEPENDENCY"
	CodeVersionMismatch    Code = "VERSION_MISMATCH"

	// Resource state errors
	CodeGone               Code = "GONE"
	CodePreconditionFailed Code = "PRECONDITION_FAILED"

	// External service errors
	CodeExternalService Code = "EXTERNAL_SERVICE_ERROR"
	CodeDatabaseError   Code = "DATABASE_ERROR"
)

Common error codes

func (Code) String

func (c Code) String() string

String returns the string representation of the error code

type Detail

type Detail interface {
	Field() string      // Field name (if applicable)
	Code() Code         // Detail-specific error code
	Message() string    // Detail-specific message
	Value() interface{} // The value that caused the error
}

Detail represents a specific error detail (e.g., field validation error)

func NewDetail

func NewDetail(field string, code Code, message string, value interface{}) Detail

NewDetail creates a new Detail

type Error

type Error interface {
	error // Embeds standard error interface

	// Core error information
	Code() Code      // Internal error code (e.g., VALIDATION_FAILED)
	Message() string // Human-readable message

	// Protocol-specific codes
	HTTPStatus() int      // HTTP status code (400, 500, etc.)
	GRPCCode() codes.Code // gRPC status code

	// Context and details
	Details() []Detail // Field-level or additional error details
	Cause() error      // Underlying error (for wrapping)

	// Metadata
	Timestamp() time.Time // When the error occurred
	RequestID() string    // Request correlation ID
	Service() string      // Service that generated the error
}

Error represents a structured error with rich context

func AlreadyExists

func AlreadyExists(resource string, identifier interface{}, opts ...Option) Error

AlreadyExists creates an already exists error

func As

func As(err error) (Error, bool)

As extracts an Error from the error chain

func Conflict

func Conflict(message string, opts ...Option) Error

Conflict creates a conflict error

func Forbidden

func Forbidden(message string, opts ...Option) Error

Forbidden creates a forbidden error

func InternalError

func InternalError(message string, opts ...Option) Error

InternalError creates an internal error

func InvalidArgument

func InvalidArgument(message string, opts ...Option) Error

InvalidArgument creates an invalid input error

func InvalidFormat

func InvalidFormat(field string, value interface{}, expectedFormat string, opts ...Option) Error

InvalidFormat creates an invalid format validation error

func MissingField

func MissingField(field string, opts ...Option) Error

MissingField creates a missing field validation error

func New

func New(code Code, opts ...Option) Error

New creates a new Error with the given code and options

func NotFound

func NotFound(resource string, identifier interface{}, opts ...Option) Error

NotFound creates a not found error

func OutOfRange

func OutOfRange(field string, value interface{}, min, max interface{}, opts ...Option) Error

OutOfRange creates an out of range validation error

func RateLimited

func RateLimited(message string, opts ...Option) Error

RateLimited creates a rate limited error

func ServiceUnavailable

func ServiceUnavailable(message string, opts ...Option) Error

ServiceUnavailable creates a service unavailable error

func Timeout

func Timeout(message string, opts ...Option) Error

Timeout creates a timeout error

func Unauthenticated

func Unauthenticated(message string, opts ...Option) Error

Unauthenticated creates an unauthenticated error

func Unauthorized

func Unauthorized(message string, opts ...Option) Error

Unauthorized creates an unauthorized error (alias for Unauthenticated for clarity)

func ValidationError

func ValidationError(opts ...ValidationOption) Error

ValidationError creates a validation error using functional options

func ValidationFailed

func ValidationFailed(message string, opts ...Option) Error

ValidationFailed creates a validation error with field details

func Wrap

func Wrap(err error, code Code, opts ...Option) Error

Wrap wraps an existing error with additional context

func WrapInternal

func WrapInternal(err error, message string, opts ...Option) Error

WrapInternal wraps an error as an internal error

func WrapNotFound

func WrapNotFound(err error, resource string, identifier interface{}, opts ...Option) Error

WrapNotFound wraps an error as a not found error

func WrapValidation

func WrapValidation(err error, message string, opts ...Option) Error

WrapValidation wraps an error as a validation error

type Option

type Option func(*errorImpl)

Option represents a functional option for configuring an Error

func WithDetail

func WithDetail(field string, code Code, message string, value interface{}) Option

WithDetail adds a detail to the error

func WithDetails

func WithDetails(details ...Detail) Option

WithDetails adds multiple details to the error

func WithGRPCCode

func WithGRPCCode(code codes.Code) Option

WithGRPCCode sets the gRPC status code

func WithHTTPStatus

func WithHTTPStatus(status int) Option

WithHTTPStatus sets the HTTP status code

func WithMessage

func WithMessage(message string) Option

WithMessage sets the human-readable error message

func WithRequestID

func WithRequestID(requestID string) Option

WithRequestID sets the request correlation ID

func WithService

func WithService(service string) Option

WithService sets the service that generated the error

type ValidationOption

type ValidationOption func(*validationConfig)

ValidationOption configures validation errors

func WithCustomValidation

func WithCustomValidation(field string, code Code, message string, value interface{}) ValidationOption

WithCustomValidation adds a custom field error

func WithInvalidFormat

func WithInvalidFormat(field string, value interface{}, expectedFormat string) ValidationOption

WithInvalidFormat adds an invalid format error

func WithOutOfRange

func WithOutOfRange(field string, value interface{}, min, max interface{}) ValidationOption

WithOutOfRange adds an out of range error

func WithRequiredField

func WithRequiredField(field string) ValidationOption

WithRequiredField adds a required field error

func WithValidationDetail

func WithValidationDetail(detail Detail) ValidationOption

WithValidationDetail adds a pre-built detail

func WithValidationDetails

func WithValidationDetails(details ...Detail) ValidationOption

WithValidationDetails adds multiple pre-built details

func WithValidationMessage

func WithValidationMessage(message string) ValidationOption

WithValidationMessage sets the overall validation message

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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