Documentation
¶
Overview ¶
Package errorx is a structured error toolkit for Go services.
An AppError carries a stable string code, a numeric code, an HTTP status, a localized user-facing message, and arbitrary structured fields. It wraps an underlying error, so errors.Is and errors.As keep working across layers.
err := errorx.New(errorx.ErrNotFound, "user lookup failed").
WithField("user_id", id).
WithDetails("no row in users table")
if errorx.Is(err, errorx.ErrNotFound) {
errorx.WriteProblem(w, err, r.URL.Path)
}
HTTP responses ¶
Both halves of a response are written by this package. On success, WriteOK, WriteCreated, WriteNoContent, and WriteJSON write the resource itself with no envelope; WriteResult takes a payload and an error and writes whichever applies, so a handler cannot send both or neither.
WriteProblem writes an error as RFC 9457 problem details: the status, the application/problem+json content type, and a body holding only the vetted members (type, title, status, detail, instance, plus the code, numeric_code, and validation extensions). AppError marshals to the same shape, so the internal fields — Message, Fields, Err, Stack, Input, Output — cannot reach a client even by accident. An error that is not an AppError becomes an opaque 500, because an error that never passed through errorx has not been vetted for what it exposes. SetProblemBaseURI turns codes into dereferenceable type URIs; SetProblemLanguage picks the language of the title.
WriteProblemRequest is the same thing driven by the request: it localizes the title from Accept-Language (see NegotiateLanguage and WithLanguage) and echoes the context's request ID as a request_id member, so the client and the logs name the same request. AppError.WithExtension adds further RFC 9457 §3.2 extension members, rendered at the document's top level; whatever must not reach a client goes in AppError.WithField instead.
Registry ¶
Every code is registered once with its severity, category, layer, retry policy, HTTP status, and per-language user message. Given a code alone the registry answers how to treat the error: GetSeverity, GetCategory, GetLayer, IsRetryable, GetRetryPolicy, ShouldAlertOps, GetHTTPStatus, GetNumericCode, and GetUserMessage.
errorx ships infrastructure codes only — repository, service, handler, and the external-service codes used by the adapters. Applications register their own codes at startup with RegisterError, RegisterErrors, or their panicking forms MustRegisterError and MustRegisterErrors, and adjust individual codes with ConfigureError, UpdateUserMessage, and SetHTTPStatus:
errorx.MustRegisterError(errorx.CustomError{
Code: "USER_NOT_FOUND", Numeric: "6001", HTTPStatus: 404,
Severity: errorx.SeverityMedium, Category: errorx.CategoryData,
Layer: errorx.LayerDomain, ServiceCode: errorx.ErrServiceNotFound,
Message: errorx.UserMessage{En: "User not found."},
})
A registered code then answers like a built-in one everywhere: New and Wrap resolve its status, severity, category, and localized message, and WriteProblem renders it. A definition the registry could not answer for is rejected instead of registered — see RegisterError for the rules — and RegisterErrors applies a batch all-or-nothing. IsRegistered, LookupError, and RegisteredErrors read the table back; UnregisterError removes a code completely. Registration is safe to call concurrently with error construction.
RegisterDomainCode and RegisterDomainCodes are the older names for the same table, kept for compatibility; they perform no validation.
ValidateRegistry and ValidateRegistryErr check the finished table for duplicate numeric codes, missing statuses or translations, and retry policies that contradict themselves.
Layers ¶
Errors are translated as they cross layers rather than leaked upward. Each layer has its own code set, a New/Wrap pair, and a mapper into the next layer:
- domain: DOMAIN_* codes, NewDomainError, WrapDomainError, MapDomainToServiceError
- infrastructure: INFRA_* codes, NewInfraError, WrapInfraError, MapInfraToServiceError
- repository: REPO_* codes, NewRepoError, WrapRepoError, MapRepoToServiceError
- application: APP_* codes, NewApplicationError, WrapApplicationError, MapServiceToHandlerError
- service, the three-layer name for the application layer: SERVICE_* codes, NewServiceError, WrapServiceError, MapServiceToHandlerError
- handler, DDD's presentation layer: HANDLER_* codes, NewHandlerError, WrapHandlerError, WriteProblem, MapToHTTPStatus
MapToServiceError and MapToApplicationError are the catch-alls: give either a domain, infrastructure, repository, or raw error and it returns the right AppError for that layer.
Two rules govern the handoff. Business meaning travels: a DOMAIN_* or APP_* code reaches the handler intact, with its registered status and user message. Mechanism does not: an INFRA_* or REPO_* code is always translated at the boundary, so a client never sees "connection pool exhausted" — though the original error stays in the chain for errors.Is and for logs.
GetLayer reports the layer of any code; IsDomainError and IsInfraError distinguish a violated business rule from a broken mechanism.
Domain packages need not import errorx: a type satisfies DomainError just by having Error and Code methods, and MapDomainToServiceError accepts it. Register such codes with RegisterDomainCode and Layer set to LayerDomain so the registry classifies them without relying on the code prefix.
Multiple failures ¶
Two shapes, two tools. A request that fails validation in several places is collected with NewValidation and returned once, as an ordinary AppError whose Validation field lists every bad field:
v := errorx.NewValidation()
v.Add("email", errorx.ErrValidation, "must be an email")
v.Add("age", errorx.ErrInvalidInput, "must be at least 18")
if err := v.Err(); err != nil {
return err
}
Independent operations that fail separately — a batch, a fan-out — are combined with Join into a MultiError. It behaves like the most serious member for status and message purposes, while errors.Is and errors.As still see them all. AllCodes, HasCode, Split, and Flatten inspect the set; RecordGlobal and ErrorChain.RecordAll count each member rather than the aggregate.
Sub-packages ¶
Driver failures are normalized into an AppError by the adapters under ./adapter — postgres, mysql, mongo, clickhouse, sql, redis, minio, kafka, rabbitmq, nats, asynq, firebase, telegram, and eventbus — each exposing a HandleError function. Only the adapter you import pulls in its driver; the root package stays driver-free. Alert delivery lives in ./reporter, and error persistence in ./logwriter.
Adapters classify on the driver's typed errors — a protocol code, an error number, a server label — never on error text, and they are built on the shared machinery in ./adapter and verified against ./adapter/adaptertest. Two properties hold across all of them: the original error stays wrapped so errors.Is still reaches the driver's sentinels, and driver text never reaches the client-facing Details field.
An adapter picks its code family by what it talks to. Stores the application owns — databases, caches, object stores — classify into the REPO_* codes, so MapRepoToServiceError translates them upward like any other repository error. Somebody else's service — brokers, push providers, third-party APIs — classifies into an EXT_* code from the numeric blocks reserved in codes_external.go.
Observability ¶
ErrorMetrics counts errors by code, severity, and category. ErrorHookManager fans every recorded error out to hooks such as LoggingHook, AlertingHook, and MetricsHook. ErrorChain reconstructs the per-request error path, SLOTracker tracks error budgets, Sampler caps hot-code volume, and RateMonitor fires when the error rate spikes.
Retries ¶
RetryWithBackoff and friends drive retries from the registry, so only codes whose policy permits it are retried. SafeExecute converts a panic into an AppError via RecoverFromPanic.
Index ¶
- Constants
- Variables
- func AllCodes(err error) []string
- func ChainHook(chain *ErrorChain) func(ctx context.Context, err *AppError)
- func ConfigureError(code string, config ErrorDetailConfig)
- func GetCaller(skip int) (file, function string)
- func GetCode(err error) string
- func GetDomainNumericCode(code string) string
- func GetDomainServiceCode(code string) string
- func GetHTTPStatus(code string) int
- func GetNumericCode(code string) string
- func GetUserMessage(code, lang string) string
- func GetUserMessageWithDetails(code, lang, details string) string
- func HasCode(err error, code string) bool
- func Is(err error, code string) bool
- func IsDomainError(err error) bool
- func IsInfraError(err error) bool
- func IsRegistered(code string) bool
- func IsRetryable(code string) bool
- func Join(errs ...error) error
- func LanguageFromContext(ctx context.Context) string
- func LogError(logger *zap.Logger, err error)
- func LogInfo(logger *zap.Logger, err error, message string)
- func LogWarn(logger *zap.Logger, err error)
- func MapToHTTPStatus(code string) int
- func MapToServiceError(err error) error
- func MustRegisterError(c CustomError)
- func MustRegisterErrors(codes ...CustomError)
- func NegotiateLanguage(header string) string
- func RateMonitorHook(monitor *RateMonitor) func(error)
- func RecordErrorGlobal(ctx context.Context, err *AppError)
- func RecordGlobal(ctx context.Context, err error)
- func RegisterDomainCode(c DomainCode)
- func RegisterDomainCodes(codes ...DomainCode)
- func RegisterError(c CustomError) error
- func RegisterErrors(codes ...CustomError) error
- func RemoveError(code string)
- func ResolverHook(resolver *Resolver) func(ctx context.Context, err *AppError)
- func RetryExponential(ctx context.Context, maxAttempts int, initialDelay time.Duration, ...) error
- func RetryImmediate(ctx context.Context, maxAttempts int, fn func() error) error
- func RetryLinear(ctx context.Context, maxAttempts int, delay time.Duration, fn func() error) error
- func RetryWithBackoff(ctx context.Context, config RetryConfig, fn func() error) error
- func SLOMiddlewareHook(tracker *SLOTracker) func(ctx context.Context, err *AppError)
- func SafeExecute(ctx context.Context, fn func() error) (err error)
- func SafeExecuteWithRetry(ctx context.Context, fn func() error) error
- func SetHTTPStatus(code string, status int)
- func SetProblemBaseURI(base string)
- func SetProblemLanguage(lang string)
- func SetReporter(r Reporter)
- func ShouldAlertOps(code string) bool
- func UnregisterDomainCode(code string)
- func UnregisterError(code string)
- func UpdateUserMessage(code string, msg UserMessage)
- func ValidateRegistryErr() error
- func WithErrorContext(ctx context.Context, ec *ErrorContext) context.Context
- func WithLanguage(ctx context.Context, lang string) context.Context
- func WithRetry(ctx context.Context, fn func() error) error
- func WriteCreated(w http.ResponseWriter, location string, payload any) error
- func WriteJSON(w http.ResponseWriter, status int, payload any) error
- func WriteNoContent(w http.ResponseWriter)
- func WriteOK(w http.ResponseWriter, payload any) error
- func WriteProblem(w http.ResponseWriter, err error, instance string) error
- func WriteProblemCtx(ctx context.Context, w http.ResponseWriter, err error, instance string) error
- func WriteProblemRequest(w http.ResponseWriter, r *http.Request, err error) error
- func WriteResult(w http.ResponseWriter, status int, payload any, err error, instance string) error
- func WriteResultCtx(ctx context.Context, w http.ResponseWriter, status int, payload any, err error, ...) error
- func WriteResultRequest(w http.ResponseWriter, r *http.Request, status int, payload any, err error) error
- type AppError
- func AutoSource(err *AppError) *AppError
- func AutoSourceSkip(err *AppError, skip int) *AppError
- func Flatten(err error) []*AppError
- func MapDomainToServiceError(err error) *AppError
- func MapInfraToServiceError(err error) *AppError
- func MapRepoToServiceError(err error, notFoundCode ...string) *AppError
- func MapServiceToHandlerError(err error) *AppError
- func MapToApplicationError(err error) *AppError
- func New(code, message string) *AppError
- func NewApplicationError(code, message string) *AppError
- func NewBadRequest(message string) *AppError
- func NewConflict(message string) *AppError
- func NewDomainError(code, message string) *AppError
- func NewForbidden(message string) *AppError
- func NewHandlerError(code, message string) *AppError
- func NewInfraError(code, message string) *AppError
- func NewInternalError(message string) *AppError
- func NewNotFound(message string) *AppError
- func NewRepoError(code, message string) *AppError
- func NewServiceError(code, message string) *AppError
- func NewTimeoutError(message string) *AppError
- func NewUnauthorized(message string) *AppError
- func NewValidationError(message string) *AppError
- func RecoverFromPanic(ctx context.Context) *AppError
- func Split(err error) (retryable, fatal []*AppError)
- func WithCaller(err *AppError, skip int) *AppError
- func WithSource(err *AppError, file, function string) *AppError
- func Wrap(err error, code, message string) *AppError
- func WrapApplicationError(err error, code, message string) *AppError
- func WrapBadRequest(err error, message string) *AppError
- func WrapConflict(err error, message string) *AppError
- func WrapDomainError(err error, code, message string) *AppError
- func WrapForbidden(err error, message string) *AppError
- func WrapHandlerError(err error, code, message string) *AppError
- func WrapInfraError(err error, code, message string) *AppError
- func WrapInternal(err error, message string) *AppError
- func WrapNotFound(err error, message string) *AppError
- func WrapRepoError(err error, code, message string) *AppError
- func WrapServiceError(err error, code, message string) *AppError
- func WrapUnauthorized(err error, message string) *AppError
- func (e *AppError) Error() string
- func (e *AppError) Fingerprint() string
- func (e *AppError) GetCategory() ErrorCategory
- func (e *AppError) GetMetadata() ErrorMetadata
- func (e *AppError) GetSeverity() ErrorSeverity
- func (e *AppError) IsRetryable() bool
- func (e *AppError) MarshalJSON() ([]byte, error)
- func (e *AppError) Problem(instance string) Problem
- func (e *AppError) ProblemCtx(ctx context.Context, instance string) Problem
- func (e *AppError) String() string
- func (e *AppError) Unwrap() error
- func (e *AppError) WithContext(ctx context.Context) *AppError
- func (e *AppError) WithDetails(details string) *AppError
- func (e *AppError) WithExtension(key string, value any) *AppError
- func (e *AppError) WithField(key string, value any) *AppError
- func (e *AppError) WithInput(input any) *AppError
- func (e *AppError) WithMetadata(key string, value any) *AppError
- func (e *AppError) WithOperation(operation string) *AppError
- func (e *AppError) WithOutput(output any) *AppError
- func (e *AppError) WithResource(resource, resourceID string) *AppError
- func (e *AppError) WithRetryAfter(d time.Duration) *AppError
- func (e *AppError) WithSuggestion(suggestion string) *AppError
- func (e *AppError) WithTag(tag string) *AppError
- type ChainEntry
- type ContextKey
- type CustomError
- type DomainCode
- type DomainError
- type ErrorCategory
- type ErrorChain
- type ErrorContext
- type ErrorDefinition
- type ErrorDetailConfig
- type ErrorHook
- type ErrorHookManager
- type ErrorLayer
- type ErrorMetadata
- type ErrorMetrics
- type ErrorSeverity
- type FieldError
- type MultiError
- type Problem
- type RateMonitor
- type RateMonitorConfig
- type RegistryProblem
- type Reporter
- type ResolutionAction
- type Resolver
- type RetryConfig
- type RetryPolicy
- type RetryStrategy
- type SLOConfig
- type SLOStats
- type SLOTracker
- type Sampler
- type SamplerConfig
- type UserMessage
- type ValidationBuilder
- func (v *ValidationBuilder) Add(field, code, message string) *ValidationBuilder
- func (v *ValidationBuilder) AddErr(field string, err error) *ValidationBuilder
- func (v *ValidationBuilder) Err() *AppError
- func (v *ValidationBuilder) Fields() []FieldError
- func (v *ValidationBuilder) HasErrors() bool
- func (v *ValidationBuilder) Len() int
- func (v *ValidationBuilder) WithLang(lang string) *ValidationBuilder
Examples ¶
Constants ¶
const ( // The use case failed for a reason none of the other codes describe. ErrAppUseCaseFailed = "APP_USE_CASE_FAILED" CodeAppUseCaseFailed = "9001" // The incoming command or query is malformed. ErrAppInvalidCommand = "APP_INVALID_COMMAND" CodeAppInvalidCommand = "9002" // A precondition of the use case did not hold. ErrAppPreconditionFailed = "APP_PRECONDITION_FAILED" CodeAppPreconditionFailed = "9003" // The caller is not authenticated. // The caller is authenticated but not allowed to run this use case. ErrAppForbidden = "APP_FORBIDDEN" CodeAppForbidden = "9005" // The aggregate the use case operates on does not exist. ErrAppNotFound = "APP_NOT_FOUND" CodeAppNotFound = "9006" // The use case conflicts with the current state of the system. ErrAppConflict = "APP_CONFLICT" CodeAppConflict = "9007" // The unit of work could not be committed. ErrAppTransactionFailed = "APP_TRANSACTION_FAILED" CodeAppTransactionFailed = "9008" // A collaborator the use case orchestrates failed. ErrAppDependencyFailed = "APP_DEPENDENCY_FAILED" CodeAppDependencyFailed = "9009" ErrAppUnknown = "APP_UNKNOWN_ERROR" CodeAppUnknown = "9099" )
Application codes describe a use case that could not be carried out: the command was malformed, a precondition did not hold, or an orchestration step failed. They occupy 9000-9099.
In a three-layer clean architecture these are interchangeable with the SERVICE_* codes; APP_* exists so DDD codebases can name the layer the way they name it in the code.
const ( // 400 - Bad Request ErrBadRequest = "BAD_REQUEST" CodeBadRequest = "1001" ErrInvalidInput = "INVALID_INPUT" CodeInvalidInput = "1002" ErrValidation = "VALIDATION_ERROR" CodeValidation = "1003" // 401 - Unauthorized ErrInvalidToken = "INVALID_TOKEN" CodeInvalidToken = "1005" ErrExpiredToken = "EXPIRED_TOKEN" CodeExpiredToken = "1006" ErrRevokedToken = "REVOKED_TOKEN" CodeRevokedToken = "1007" // 403 - Forbidden ErrForbidden = "FORBIDDEN" CodeForbidden = "1008" ErrPermissionDenied = "PERMISSION_DENIED" CodePermissionDenied = "1010" ErrDisabledAccount = "DISABLED_ACCOUNT" CodeDisabledAccount = "1011" // 404 - Not Found ErrNotFound = "NOT_FOUND" CodeNotFound = "1012" ErrUserNotFound = "USER_NOT_FOUND" CodeUserNotFound = "1013" ErrSessionNotFound = "SESSION_NOT_FOUND" CodeSessionNotFound = "1014" // 409 - Conflict ErrConflict = "CONFLICT" CodeConflict = "1015" ErrAlreadyExists = "ALREADY_EXISTS" CodeAlreadyExists = "1016" // 500 - Internal Server Error ErrInternal = "INTERNAL_ERROR" CodeInternal = "1017" ErrDatabase = "DATABASE_ERROR" CodeDatabase = "1018" ErrUnknown = "UNKNOWN_ERROR" CodeUnknown = "1019" // 504 - Timeout ErrTimeout = "TIMEOUT" CodeTimeout = "1020" // Storage errors (MinIO/File Upload) ErrBucketNotFound = "BUCKET_NOT_FOUND" CodeBucketNotFound = "1021" ErrFileNotFound = "FILE_NOT_FOUND" CodeFileNotFound = "1022" ErrInvalidFileFormat = "INVALID_FILE_FORMAT" CodeInvalidFileFormat = "1023" ErrUploadFailed = "UPLOAD_FAILED" CodeUploadFailed = "1024" ErrDeleteFailed = "DELETE_FAILED" CodeDeleteFailed = "1025" )
const ( ErrExtAsynqEnqueueFailed = "EXT_ASYNQ_ENQUEUE_FAILED" CodeExtAsynqEnqueueFailed = "7021" ErrExtAsynqConnection = "EXT_ASYNQ_CONNECTION" CodeExtAsynqConnection = "7022" ErrExtAsynqTimeout = "EXT_ASYNQ_TIMEOUT" CodeExtAsynqTimeout = "7023" ErrExtAsynqPayloadError = "EXT_ASYNQ_PAYLOAD_ERROR" CodeExtAsynqPayloadError = "7024" )
External Asynq error codes
const ( ErrExtEventBusPublishFailed = "EXT_EVENTBUS_PUBLISH_FAILED" CodeExtEventBusPublishFailed = "7031" ErrExtEventBusConnection = "EXT_EVENTBUS_CONNECTION" CodeExtEventBusConnection = "7032" ErrExtEventBusTimeout = "EXT_EVENTBUS_TIMEOUT" CodeExtEventBusTimeout = "7033" ErrExtEventBusSubscribeFailed = "EXT_EVENTBUS_SUBSCRIBE_FAILED" CodeExtEventBusSubscribeFailed = "7034" )
External EventBus error codes
const ( ErrExtFirebaseSendFailed = "EXT_FIREBASE_SEND_FAILED" CodeExtFirebaseSendFailed = "7001" ErrExtFirebaseInvalidToken = "EXT_FIREBASE_INVALID_TOKEN" CodeExtFirebaseInvalidToken = "7002" ErrExtFirebaseQuotaExceeded = "EXT_FIREBASE_QUOTA_EXCEEDED" CodeExtFirebaseQuotaExceeded = "7003" )
External Firebase error codes
const ( ErrExtTelegramAPIError = "EXT_TELEGRAM_API_ERROR" CodeExtTelegramAPIError = "7011" ErrExtTelegramTimeout = "EXT_TELEGRAM_TIMEOUT" CodeExtTelegramTimeout = "7012" ErrExtTelegramConnection = "EXT_TELEGRAM_CONNECTION" CodeExtTelegramConnection = "7013" ErrExtTelegramRateLimit = "EXT_TELEGRAM_RATE_LIMIT" CodeExtTelegramRateLimit = "7014" )
External Telegram error codes
const ( ErrExtKafkaConnection = "EXT_KAFKA_CONNECTION" CodeExtKafkaConnection = "7041" ErrExtKafkaTimeout = "EXT_KAFKA_TIMEOUT" CodeExtKafkaTimeout = "7043" ErrExtKafkaTopicMissing = "EXT_KAFKA_TOPIC_MISSING" CodeExtKafkaTopicMissing = "7044" ErrExtKafkaPayload = "EXT_KAFKA_PAYLOAD" CodeExtKafkaPayload = "7045" ErrExtKafkaAuth = "EXT_KAFKA_AUTH" CodeExtKafkaAuth = "7046" ErrExtKafkaRebalance = "EXT_KAFKA_REBALANCE" CodeExtKafkaRebalance = "7047" ErrExtKafkaOffset = "EXT_KAFKA_OFFSET" CodeExtKafkaOffset = "7048" ErrExtKafkaUnknown = "EXT_KAFKA_UNKNOWN" CodeExtKafkaUnknown = "7049" )
External Kafka error codes
const ( ErrExtRabbitConnection = "EXT_RABBIT_CONNECTION" CodeExtRabbitConnection = "7051" ErrExtRabbitAuth = "EXT_RABBIT_AUTH" CodeExtRabbitAuth = "7053" ErrExtRabbitNotFound = "EXT_RABBIT_NOT_FOUND" CodeExtRabbitNotFound = "7054" ErrExtRabbitNoRoute = "EXT_RABBIT_NO_ROUTE" CodeExtRabbitNoRoute = "7055" ErrExtRabbitPrecondition = "EXT_RABBIT_PRECONDITION" CodeExtRabbitPrecondition = "7056" ErrExtRabbitNack = "EXT_RABBIT_NACK" CodeExtRabbitNack = "7057" ErrExtRabbitTimeout = "EXT_RABBIT_TIMEOUT" CodeExtRabbitTimeout = "7058" ErrExtRabbitUnknown = "EXT_RABBIT_UNKNOWN" CodeExtRabbitUnknown = "7059" )
External RabbitMQ error codes
const ( ErrExtNatsConnection = "EXT_NATS_CONNECTION" CodeExtNatsConnection = "7061" ErrExtNatsNoResponders = "EXT_NATS_NO_RESPONDERS" CodeExtNatsNoResponders = "7062" ErrExtNatsTimeout = "EXT_NATS_TIMEOUT" CodeExtNatsTimeout = "7063" ErrExtNatsMaxPayload = "EXT_NATS_MAX_PAYLOAD" CodeExtNatsMaxPayload = "7064" ErrExtNatsNotFound = "EXT_NATS_NOT_FOUND" CodeExtNatsNotFound = "7065" ErrExtNatsAuth = "EXT_NATS_AUTH" CodeExtNatsAuth = "7066" ErrExtNatsUnknown = "EXT_NATS_UNKNOWN" CodeExtNatsUnknown = "7069" )
External NATS / JetStream error codes
const ( // An aggregate would have been left in an illegal state. ErrDomainInvariant = "DOMAIN_INVARIANT_VIOLATION" CodeDomainInvariant = "8001" // A business rule rejected an otherwise well-formed operation. ErrDomainRule = "DOMAIN_RULE_VIOLATION" CodeDomainRule = "8002" // The operation is not legal from the entity's current state. ErrDomainInvalidState = "DOMAIN_INVALID_STATE" CodeDomainInvalidState = "8003" // A value object rejected its input. ErrDomainInvalidValue = "DOMAIN_INVALID_VALUE" CodeDomainInvalidValue = "8004" // The aggregate a command referred to does not exist. ErrDomainNotFound = "DOMAIN_NOT_FOUND" CodeDomainNotFound = "8005" // Another aggregate already holds the identity or uniqueness claim. ErrDomainConflict = "DOMAIN_CONFLICT" CodeDomainConflict = "8006" // Concurrent modification: the aggregate version moved underneath us. ErrDomainConcurrency = "DOMAIN_CONCURRENCY_CONFLICT" CodeDomainConcurrency = "8007" ErrDomainUnknown = "DOMAIN_UNKNOWN_ERROR" CodeDomainUnknown = "8099" )
Domain codes describe a violated business rule, not a failed mechanism: the entity refused the operation. They live in the 8xxx numeric range, leaving 6xxx free for the application-specific codes you register with RegisterDomainCode.
const ( // HTTP handler errors ErrHandlerBadRequest = "HANDLER_BAD_REQUEST" CodeHandlerBadRequest = "4000" ErrHandlerForbidden = "HANDLER_FORBIDDEN" CodeHandlerForbidden = "4003" ErrHandlerNotFound = "HANDLER_NOT_FOUND" CodeHandlerNotFound = "4004" ErrHandlerMethodNotAllowed = "HANDLER_METHOD_NOT_ALLOWED" CodeHandlerMethodNotAllowed = "4005" ErrHandlerConflict = "HANDLER_CONFLICT" CodeHandlerConflict = "4009" ErrHandlerTooManyRequests = "HANDLER_TOO_MANY_REQUESTS" CodeHandlerTooManyRequests = "4029" ErrHandlerNotImplemented = "HANDLER_NOT_IMPLEMENTED" CodeHandlerNotImplemented = "5001" ErrHandlerInternal = "HANDLER_INTERNAL_ERROR" CodeHandlerInternal = "5000" ErrHandlerUnknown = "HANDLER_UNKNOWN_ERROR" CodeHandlerUnknown = "5099" )
const ( // A connection to a dependency could not be established. ErrInfraConnection = "INFRA_CONNECTION_FAILED" CodeInfraConnection = "9101" // A dependency did not answer in time. ErrInfraTimeout = "INFRA_TIMEOUT" CodeInfraTimeout = "9102" // A dependency is reachable but refusing work. // The process is misconfigured: bad DSN, missing credentials, bad flag. ErrInfraConfig = "INFRA_CONFIG_INVALID" CodeInfraConfig = "9104" // Encoding or decoding a payload failed. ErrInfraSerialization = "INFRA_SERIALIZATION_FAILED" CodeInfraSerialization = "9105" // A read or write against a file, socket, or object store failed. ErrInfraIO = "INFRA_IO_FAILED" CodeInfraIO = "9106" // The dependency rejected our credentials or scope. ErrInfraPermissionDenied = "INFRA_PERMISSION_DENIED" CodeInfraPermissionDenied = "9107" // The requested object does not exist in the backing store. ErrInfraNotFound = "INFRA_NOT_FOUND" CodeInfraNotFound = "9108" // The write collided with something already there. ErrInfraConflict = "INFRA_CONFLICT" CodeInfraConflict = "9109" // The dependency throttled us. ErrInfraRateLimited = "INFRA_RATE_LIMITED" CodeInfraRateLimited = "9110" ErrInfraUnknown = "INFRA_UNKNOWN_ERROR" CodeInfraUnknown = "9199" )
Infrastructure codes describe a mechanism that failed — a connection, a timeout, a serialization step, a misconfiguration. They occupy 9100-9199.
The REPO_* codes stay the specific vocabulary for persistence; INFRA_* covers everything else the infrastructure layer talks to, and is what the ./adapter packages fall back to for failures with no more precise code.
const ( // Database errors ErrRepoNotFound = "REPO_NOT_FOUND" CodeRepoNotFound = "2001" ErrRepoAlreadyExists = "REPO_ALREADY_EXISTS" CodeRepoAlreadyExists = "2002" ErrRepoDatabase = "REPO_DATABASE_ERROR" CodeRepoDatabase = "2003" ErrRepoTimeout = "REPO_TIMEOUT" CodeRepoTimeout = "2004" ErrRepoConnection = "REPO_CONNECTION_ERROR" CodeRepoConnection = "2005" ErrRepoTransaction = "REPO_TRANSACTION_ERROR" CodeRepoTransaction = "2006" ErrRepoConstraint = "REPO_CONSTRAINT_VIOLATION" CodeRepoConstraint = "2007" // ErrRepoSerialization is a lost write race the caller may simply redo: // Postgres 40001/40P01, MySQL 1213/1205, a Mongo TransientTransactionError. // It is retryable, which is why it must not be folded into // ErrRepoTransaction. ErrRepoSerialization = "REPO_SERIALIZATION_FAILURE" CodeRepoSerialization = "2008" // ErrRepoUnavailable is the store being up but unable to serve right now: // failover, replica-set election, connection limit reached. // ErrRepoReadOnly is a write sent to a node that only accepts reads: // a Redis replica, MySQL --read-only, a Postgres standby. ErrRepoReadOnly = "REPO_READ_ONLY" CodeRepoReadOnly = "2010" // ErrRepoQuotaExceeded is the store refusing writes for lack of room: // disk full, memory limit, storage quota. ErrRepoQuotaExceeded = "REPO_QUOTA_EXCEEDED" CodeRepoQuotaExceeded = "2011" // ErrRepoUnauthorized is a credential or privilege failure against the // store. Never retryable, and never a 401 to the client — it is our // misconfiguration, not the caller's. ErrRepoUnknown = "REPO_UNKNOWN_ERROR" CodeRepoUnknown = "2099" )
const ( // Business logic errors ErrServiceInvalidInput = "SERVICE_INVALID_INPUT" CodeServiceInvalidInput = "3001" ErrServiceValidation = "SERVICE_VALIDATION_ERROR" CodeServiceValidation = "3002" ErrServiceNotFound = "SERVICE_NOT_FOUND" CodeServiceNotFound = "3003" ErrServiceAlreadyExists = "SERVICE_ALREADY_EXISTS" CodeServiceAlreadyExists = "3004" ErrServiceForbidden = "SERVICE_FORBIDDEN" CodeServiceForbidden = "3006" ErrServiceConflict = "SERVICE_CONFLICT" CodeServiceConflict = "3007" ErrServiceBusinessRule = "SERVICE_BUSINESS_RULE_VIOLATION" CodeServiceBusinessRule = "3008" ErrServiceDependency = "SERVICE_DEPENDENCY_ERROR" CodeServiceDependency = "3009" // Authz specific errors ErrServiceRoleNotFound = "SERVICE_ROLE_NOT_FOUND" CodeServiceRoleNotFound = "3010" ErrServicePermissionNotFound = "SERVICE_PERMISSION_NOT_FOUND" CodeServicePermissionNotFound = "3011" ErrServicePolicyViolation = "SERVICE_POLICY_VIOLATION" CodeServicePolicyViolation = "3012" ErrServiceScopeNotFound = "SERVICE_SCOPE_NOT_FOUND" CodeServiceScopeNotFound = "3013" ErrServiceRelationNotFound = "SERVICE_RELATION_NOT_FOUND" CodeServiceRelationNotFound = "3014" ErrServiceUnknown = "SERVICE_UNKNOWN_ERROR" CodeServiceUnknown = "3099" )
const JSONMediaType = "application/json; charset=utf-8"
JSONMediaType is the media type for successful JSON responses. Errors use ProblemMediaType instead.
const ProblemMediaType = "application/problem+json"
ProblemMediaType is the media type RFC 9457 defines for problem details. Responses carrying a Problem must use it instead of application/json.
Variables ¶
var ( // Database errors ErrTestDB = errors.New("database error") ErrTestDBConnection = errors.New("database connection error") ErrTestConnectionTimeout = errors.New("connection timeout") ErrTestSelectQuery = errors.New("select query error") ErrTestCountError = errors.New("count error") // Constraint errors ErrTestDuplicateKey = errors.New("duplicate key value violates unique constraint") ErrTestForeignKey = errors.New("foreign key constraint violation") ErrTestUniqueConstraint = errors.New("unique constraint violation") ErrTestCheckConstraint = errors.New("check constraint violation") // Validation errors ErrTestInvalidPhone = errors.New("invalid phone format") ErrTestInvalidUserID = errors.New("invalid user ID") ErrTestInvalidCompanyID = errors.New("invalid company ID") ErrTestInvalidFilter = errors.New("invalid filter") ErrTestInvalidSession = errors.New("invalid session") ErrTestValidationFailed = errors.New("validation failed") // Password errors ErrTestPasswordHashEmpty = errors.New("password hash cannot be empty") // Permission errors ErrTestPermissionDenied = errors.New("permission denied for table") // Lock errors ErrTestDatabaseLocked = errors.New("database is locked") // Redis errors ErrTestRedisConnection = errors.New("redis connection failed") ErrTestRedisScan = errors.New("redis scan error") ErrTestRedisDialTCP = errors.New("dial tcp: connection refused") ErrTestRedisIOTimeout = errors.New("i/o timeout") ErrTestRedisContextDeadline = errors.New("context deadline exceeded") ErrTestRedisWrongPass = errors.New("WRONGPASS invalid username-password pair") ErrTestRedisWrongType = errors.New("WRONGTYPE Operation against a key holding the wrong kind of value") ErrTestRedisOOM = errors.New("OOM command not allowed when used memory > 'maxmemory'") ErrTestRedisReadOnly = errors.New("READONLY You can't write against a read only replica") ErrTestRedisClusterDown = errors.New("CLUSTERDOWN The cluster is down") ErrTestRedisNoScript = errors.New("NOSCRIPT No matching script. Please use EVAL") ErrTestRedisNoAuth = errors.New("NOAUTH Authentication required") ErrTestRedisEOF = errors.New("EOF") ErrTestRedisBrokenPipe = errors.New("write: broken pipe") ErrTestRedisRandom = errors.New("some random redis error") ErrTestRedisError = errors.New("some redis error") // User/Session errors ErrTestUserNotFound = errors.New("user not found") ErrTestSessionNotFound = errors.New("session not found") ErrTestSessionCreationFailed = errors.New("session creation failed") ErrTestSessionRevokeFailed = errors.New("session revoke failed") // Operation errors ErrTestDeleteFailed = errors.New("delete failed") ErrTestUpdateFailed = errors.New("update failed") ErrTestScanError = errors.New("scan error") // Generic errors ErrTestHandler = errors.New("handler error") ErrTestService = errors.New("service error") ErrTestRegular = errors.New("regular error") ErrTestBase = errors.New("base error") )
Common test errors that can be wrapped with context in test files.
var SupportedLanguages = []string{"en", "uz", "ru"}
SupportedLanguages are the languages a registered message can be written in, in the order they are preferred when a client expresses no preference of its own. It mirrors the fields of UserMessage.
Functions ¶
func ChainHook ¶
func ChainHook(chain *ErrorChain) func(ctx context.Context, err *AppError)
ChainHook returns an ErrorHook that records errors into the chain.
func ConfigureError ¶
func ConfigureError(code string, config ErrorDetailConfig)
ConfigureError updates both message and status for an error code
func GetCaller ¶
GetCaller returns the file and function name of the caller Skip levels: 0 = GetCaller itself, 1 = caller of GetCaller, etc. Returns relative path from project root (internal/repo/...) and short function name
func GetDomainNumericCode ¶
GetDomainNumericCode returns numeric code for a domain error code, or empty string.
func GetDomainServiceCode ¶
GetDomainServiceCode returns the service error code a domain code maps to.
func GetHTTPStatus ¶
GetHTTPStatus returns the HTTP status for an error code, or 0 if not found
func GetNumericCode ¶
GetNumericCode returns numeric code by error type
func GetUserMessage ¶
GetUserMessage returns user-friendly message for error code in specified language
func GetUserMessageWithDetails ¶
GetUserMessageWithDetails returns user message with additional details
func HasCode ¶
HasCode reports whether code appears anywhere in err, including inside a MultiError.
This is the deep counterpart to Is, which answers only for the dominant error. Reach for HasCode when any occurrence should trigger a branch.
func IsDomainError ¶
IsDomainError reports whether err carries a domain-layer code — either one of the built-in DOMAIN_* codes, an application code registered with LayerDomain, or a type implementing DomainError.
func IsInfraError ¶
IsInfraError reports whether err came from the infrastructure layer — INFRA_*, REPO_*, or an EXT_* adapter code.
func IsRegistered ¶
IsRegistered reports whether a code has been registered — either by errorx or by the application. An unregistered code still works, but answers with defaults: numeric code "9999", the generic user message, and no HTTP status.
func IsRetryable ¶
IsRetryable determines if an error is retryable.
A registered code answers for itself: RegisterDomainCode stores a RetryPolicy, and that policy wins over the built-in table below. Without this lookup every registered code (including every EXT_* adapter code) would fall through to the default and report false, so RetryWithBackoff would never retry it.
func Join ¶
Join combines errors into one. Nil entries are dropped; if nothing is left it returns nil, and if exactly one error is left it returns that error unchanged rather than wrapping a single failure in aggregate machinery.
A nested MultiError is flattened, so joining results of joins does not build a tree that later readers have to walk.
func LanguageFromContext ¶
LanguageFromContext returns the language the context carries, falling back to the language set by SetProblemLanguage.
func LogError ¶
LogError logs error using zap logger with all available fields Usage in Handler layer ONLY:
errors.LogError(logger, err)
func MapToHTTPStatus ¶
MapToHTTPStatus maps error code to HTTP status code
func MapToServiceError ¶
MapToServiceError converts any error to a service-layer AppError. It accepts a domain error, an application error, a repository or infrastructure error, an external adapter error, or a raw error.
func MustRegisterError ¶
func MustRegisterError(c CustomError)
MustRegisterError is RegisterError for package-level registration, where there is no caller to return an error to. It panics on an invalid definition.
func MustRegisterErrors ¶
func MustRegisterErrors(codes ...CustomError)
MustRegisterErrors is RegisterErrors that panics instead of returning.
func NegotiateLanguage ¶
NegotiateLanguage picks the best supported language for an Accept-Language header, honoring q-values and matching a subtag to its base language, so "uz-UZ" selects "uz" and "en-GB;q=0.8, ru;q=0.9" selects "ru".
It returns "" when the header is empty or names nothing supported, which the caller should read as "use the default" rather than as an error: a client asking for a language a service has no messages in is not a failed request.
func RateMonitorHook ¶
func RateMonitorHook(monitor *RateMonitor) func(error)
RateMonitorHook returns a function that feeds errors into the rate monitor.
func RecordErrorGlobal ¶
RecordErrorGlobal records an error in global metrics and executes hooks
func RecordGlobal ¶
RecordGlobal records err in global metrics and runs the hooks, counting each failure inside a MultiError separately.
RecordErrorGlobal takes a single *AppError, so handing it an aggregate records only the dominant one and silently undercounts the rest. Prefer this function anywhere an aggregate can reach.
func RegisterDomainCode ¶
func RegisterDomainCode(c DomainCode)
RegisterDomainCode adds a code to the registry, overwriting any previous registration of the same code. Call it during application startup, before any goroutine reads the registry.
func RegisterDomainCodes ¶
func RegisterDomainCodes(codes ...DomainCode)
RegisterDomainCodes registers a batch of codes in order.
func RegisterError ¶
func RegisterError(c CustomError) error
RegisterError adds an application error code to the registry, overwriting any previous registration of the same code, and returns what is wrong with the definition rather than registering something the rest of the package cannot answer for.
Zero fields are filled in: HTTPStatus becomes 500, Severity becomes SeverityMedium, Category becomes CategorySystem, and Layer is derived from the code prefix the way GetLayer derives it.
It is safe to call concurrently with error construction; registration during startup is still the sane order.
Example ¶
Applications register their own codes at startup. From then on the code is indistinguishable from a built-in one: the registry answers for its status, severity, layer, and localized message, and WriteProblem renders it.
package main
import (
"fmt"
"net/http/httptest"
"github.com/bakhod1r/errorx"
)
func main() {
errorx.MustRegisterError(errorx.CustomError{
Code: "WALLET_INSUFFICIENT_FUNDS",
Numeric: "6001",
HTTPStatus: 409,
Severity: errorx.SeverityMedium,
Category: errorx.CategoryBusiness,
Layer: errorx.LayerDomain,
ServiceCode: errorx.ErrServiceBusinessRule,
Message: errorx.UserMessage{
En: "Your balance is too low for this transfer.",
Uz: "Balansingiz bu o'tkazma uchun yetarli emas.",
Ru: "На балансе недостаточно средств для перевода.",
},
})
defer errorx.UnregisterError("WALLET_INSUFFICIENT_FUNDS")
err := errorx.New("WALLET_INSUFFICIENT_FUNDS", "balance 40 < amount 100").
WithField("balance", 40)
rec := httptest.NewRecorder()
_ = errorx.WriteProblem(rec, err, "/wallet/transfer")
fmt.Println(rec.Code)
fmt.Println(rec.Body.String())
}
Output: 409 {"type":"about:blank","title":"Your balance is too low for this transfer.","status":409,"instance":"/wallet/transfer","code":"WALLET_INSUFFICIENT_FUNDS","numeric_code":6001}
Example (Validation) ¶
A definition the registry cannot answer for is rejected at registration rather than at the first request that hits it.
package main
import (
"fmt"
"github.com/bakhod1r/errorx"
)
func main() {
err := errorx.RegisterError(errorx.CustomError{
Code: "ORDER_REJECTED",
Numeric: "1012", // already owned by NOT_FOUND
Message: errorx.UserMessage{En: "The order was rejected."},
})
fmt.Println(err)
}
Output: errorx: cannot register "ORDER_REJECTED": numeric code 1012 is already used by "NOT_FOUND"
func RegisterErrors ¶
func RegisterErrors(codes ...CustomError) error
RegisterErrors registers a batch atomically: every definition is validated first, and if any one of them is rejected none are registered. That keeps a typo in the tenth code from leaving the first nine live.
func RemoveError ¶
func RemoveError(code string)
RemoveError removes both the cached HTTP status and user message for an error code.
func ResolverHook ¶
ResolverHook returns an ErrorHook that attempts auto-resolution.
func RetryExponential ¶
func RetryExponential(ctx context.Context, maxAttempts int, initialDelay time.Duration, fn func() error) error
RetryExponential executes a function with exponential backoff
func RetryImmediate ¶
RetryImmediate executes a function with immediate retry (no delay)
func RetryLinear ¶
RetryLinear executes a function with linear backoff
func RetryWithBackoff ¶
func RetryWithBackoff(ctx context.Context, config RetryConfig, fn func() error) error
RetryWithBackoff executes a function with retry logic and exponential backoff
func SLOMiddlewareHook ¶
func SLOMiddlewareHook(tracker *SLOTracker) func(ctx context.Context, err *AppError)
SLOMiddlewareHook returns an ErrorHook that records errors for SLO tracking.
func SafeExecute ¶
SafeExecute executes a function and recovers from panics
func SafeExecuteWithRetry ¶
SafeExecuteWithRetry executes a function with panic recovery and retry logic
func SetHTTPStatus ¶
SetHTTPStatus updates the HTTP status for an error code
func SetProblemBaseURI ¶
func SetProblemBaseURI(base string)
SetProblemBaseURI sets the base URI that problem type URIs are built from.
With a base of "https://errors.example.com/", the code HANDLER_NOT_FOUND becomes "https://errors.example.com/handler-not-found". With no base — the default — every problem reports the RFC's "about:blank", and clients branch on the Code member instead. Set it once at startup.
func SetProblemLanguage ¶
func SetProblemLanguage(lang string)
SetProblemLanguage sets the language used for the Title of problems built from a code's registered message. Defaults to "en". Set it once at startup; for per-request languages, build the Problem and overwrite Title.
func SetReporter ¶
func SetReporter(r Reporter)
func ShouldAlertOps ¶
ShouldAlertOps determines if operations team should be alerted
func UnregisterDomainCode ¶
func UnregisterDomainCode(code string)
UnregisterDomainCode removes a code from the registry completely: its numeric code, severity, category, retry policy, service mapping, and layer, plus the message and HTTP status that RemoveError handles.
RemoveError alone is not enough — it clears only the message and status, so the code keeps answering GetNumericCode, GetSeverity, and the rest, and a test that registers a code leaks it into every later test in the package.
func UnregisterError ¶
func UnregisterError(code string)
UnregisterError removes an application code from the registry completely. It is UnregisterDomainCode under the layer-neutral name.
func UpdateUserMessage ¶
func UpdateUserMessage(code string, msg UserMessage)
UpdateUserMessage allows updating user message for a specific error code This is useful for customizing messages at runtime
func ValidateRegistryErr ¶
func ValidateRegistryErr() error
ValidateRegistryErr is ValidateRegistry as a single error, for callers that want to fail startup on a bad registry.
func WithErrorContext ¶
func WithErrorContext(ctx context.Context, ec *ErrorContext) context.Context
WithErrorContext adds ErrorContext to context
func WithLanguage ¶
WithLanguage returns a context that renders problem titles in lang.
It is what makes localization per-request rather than per-process: SetProblemLanguage picks the default for a service, this picks the language for one caller. Middleware normally sets it from Accept-Language or from the authenticated user's profile:
ctx := errorx.WithLanguage(r.Context(), errorx.NegotiateLanguage(r.Header.Get("Accept-Language")))
An unsupported or empty lang is ignored, so a bad header degrades to the service default instead of to an untranslated response.
func WithRetry ¶
WithRetry is a helper that wraps a function with automatic retry based on error metadata
func WriteCreated ¶
func WriteCreated(w http.ResponseWriter, location string, payload any) error
WriteCreated writes payload with 201 Created.
location is the URI of the newly created resource, sent in the Location header as RFC 9110 §10.2.2 requires; pass "" to omit it.
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, status int, payload any) error
WriteJSON writes a successful JSON response with the given status.
The payload is written as-is, with no envelope. A wrapper such as {"data": ...} is a convention, not a standard, and it forces every client to unwrap one level before it reaches the resource it asked for; the error path already has a real standard in RFC 9457, which WriteProblem implements.
The body is marshaled before any header is written, so a payload that cannot be encoded returns an error while the response is still untouched and the caller can still fall back to WriteProblem.
A nil payload writes 204 No Content regardless of the status passed, since a JSON body of "null" tells a client nothing. A nil pointer counts as nil here: a handler returning (*User)(nil) meant "nothing", and encoding/json would otherwise have written "null" with a 200.
A nil slice or map is the opposite case — it means "none", not "nothing" — so it is written as [] or {} rather than null, and a client can iterate the result without a null check.
func WriteNoContent ¶
func WriteNoContent(w http.ResponseWriter)
WriteNoContent writes 204 No Content, for a request that succeeded and has nothing to return — a delete, or an update whose result the client already has.
func WriteOK ¶
func WriteOK(w http.ResponseWriter, payload any) error
WriteOK writes payload with 200 OK.
Example ¶
A successful response carries the resource itself, with no envelope.
package main
import (
"fmt"
"net/http/httptest"
"github.com/bakhod1r/errorx"
)
func main() {
rec := httptest.NewRecorder()
_ = errorx.WriteOK(rec, map[string]any{"id": 42, "email": "a@example.com"})
fmt.Println(rec.Code)
fmt.Println(rec.Header().Get("Content-Type"))
fmt.Println(rec.Body.String())
}
Output: 200 application/json; charset=utf-8 {"email":"a@example.com","id":42}
func WriteProblem ¶
func WriteProblem(w http.ResponseWriter, err error, instance string) error
WriteProblem writes err to w as an RFC 9457 problem details response: the correct status, Content-Type: application/problem+json, and a body carrying no internal detail.
A plain error that is not an AppError becomes an opaque 500 — an error that never passed through errorx has not been vetted for what it exposes, so its text is not sent to the client. Log it before calling.
instance is the URI of this occurrence, normally r.URL.Path; pass "" to omit.
Example ¶
A failure carries RFC 9457 problem details, and nothing internal.
package main
import (
"fmt"
"net/http/httptest"
"github.com/bakhod1r/errorx"
)
func main() {
errorx.SetProblemBaseURI("https://errors.example.com/")
defer errorx.SetProblemBaseURI("")
appErr := errorx.New(errorx.ErrNotFound, "pg: no rows in result set").
WithField("user_id", 42).
WithDetails("user 42 does not exist")
rec := httptest.NewRecorder()
_ = errorx.WriteProblem(rec, appErr, "/api/v1/users/42")
fmt.Println(rec.Code)
fmt.Println(rec.Header().Get("Content-Type"))
fmt.Println(rec.Body.String())
}
Output: 404 application/problem+json {"type":"https://errors.example.com/not-found","title":"Not found","status":404,"detail":"user 42 does not exist","instance":"/api/v1/users/42","code":"NOT_FOUND","numeric_code":1012}
func WriteProblemCtx ¶
WriteProblemCtx is WriteProblem with the request's context: the title is localized to the language the context carries, and a request ID in the context is echoed as a request_id member so the client and the logs name the same request.
func WriteProblemRequest ¶
WriteProblemRequest is WriteProblemCtx with everything it needs read off the request: the context, the path as the instance, and — when the context names no language — the client's Accept-Language header.
if err != nil {
return errorx.WriteProblemRequest(w, r, err)
}
func WriteResult ¶
WriteResult writes one or the other: the problem details for err if it is non-nil, otherwise payload with the given success status.
It exists so a handler's exit is a single line that cannot accidentally send both a body and an error, or neither.
return errorx.WriteResult(w, http.StatusOK, user, err, r.URL.Path)
Example ¶
A handler's exit is one line, and it cannot send both a body and an error.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/bakhod1r/errorx"
)
func main() {
handler := func(w http.ResponseWriter, r *http.Request) {
user, err := map[string]any{"id": 42}, error(nil)
_ = errorx.WriteResult(w, http.StatusOK, user, err, r.URL.Path)
}
rec := httptest.NewRecorder()
handler(rec, httptest.NewRequest(http.MethodGet, "/api/v1/users/42", nil))
fmt.Println(rec.Code, rec.Body.String())
}
Output: 200 {"id":42}
func WriteResultCtx ¶
func WriteResultCtx(ctx context.Context, w http.ResponseWriter, status int, payload any, err error, instance string) error
WriteResultCtx is WriteResult with the request's context, so the error path is localized and carries the request ID. See WriteProblemCtx.
func WriteResultRequest ¶
func WriteResultRequest(w http.ResponseWriter, r *http.Request, status int, payload any, err error) error
WriteResultRequest is WriteResult with the context, instance, and language read off the request. It is the shortest correct exit a handler has:
user, err := svc.Get(r.Context(), id) return errorx.WriteResultRequest(w, r, http.StatusOK, user, err)
Types ¶
type AppError ¶
type AppError struct {
Type string // Error type (e.g.: "USER_NOT_FOUND")
Code string // Numeric error code (e.g.: "4041")
Message string `json:"-"` // Developer message (internal)
HTTPStatus int // HTTP status code
UserMsg string // User-facing message
Details string // Detailed explanation
Severity ErrorSeverity // Error severity
Category ErrorCategory // Error category
Suggestion string // Help suggestion
// Validation lists field-level failures. It is deliberately NOT `json:"-"`:
// naming the offending fields is the point of a validation response. Its
// contents must stay free of internal detail.
Validation []FieldError `json:"validation,omitempty"`
// Extensions are RFC 9457 §3.2 extension members: the one channel for data
// that is meant to reach the client but has no RFC member of its own — a
// balance on a payment failure, a quota on a rate limit. They are rendered
// as top-level members of the problem document, so unlike Fields they are
// public by definition: put nothing here that Fields would have protected.
Extensions map[string]any `json:"-"`
// RetryAfter is how long the client should wait before retrying. It is sent
// as the Retry-After header on the statuses RFC 9110 defines it for (429,
// 503) and on any status when set explicitly. Zero means the registry's
// retry policy decides.
RetryAfter time.Duration `json:"-"`
Fields map[string]any `json:"-"` // Additional data (may contain sensitive values)
Err error `json:"-"` // Wrapped error (may expose infra internals)
Stack []uintptr `json:"-"` // Stack trace (never expose to clients)
Input any `json:"-"` // Input data (may contain credentials/PII)
Output any `json:"-"` // Output data (may contain credentials/PII)
}
AppError custom error structure.
Security note: most of these fields MUST NEVER reach a client. They may contain internal details, wrapped infrastructure errors, stack traces, or raw request/response payloads (which can include passwords, tokens, or PII). They are for internal logging and debugging only.
That is enforced rather than documented: AppError marshals through MarshalJSON into a Problem (see problem.go), which carries only the vetted members. Sending an AppError to a client therefore means WriteProblem or Problem(instance) — never a hand-built struct over these fields.
func AutoSource ¶
AutoSource automatically adds caller info with proper skip level This should be called directly from repository/service functions
func AutoSourceSkip ¶
AutoSourceSkip is AutoSource with control over how many frames to skip. skip=0 records AutoSourceSkip's own caller, matching AutoSource; each increment steps one frame further up.
Helpers that build errors on someone else's behalf need this: without it the recorded source is the helper itself, which is the one frame nobody debugging the error cares about.
func Flatten ¶
Flatten returns every AppError reachable from err, including the members of any MultiError. A plain error contributes nothing.
This is what metrics and hooks need: counting an aggregate once would undercount by however many failures it contains.
func MapDomainToServiceError ¶
MapDomainToServiceError converts a domain error to a service-layer AppError, and returns nil for anything that is not one. It accepts both an AppError carrying a domain-layer code (see NewDomainError) and any type implementing DomainError.
The original domain code is preserved as the Type so that handlers and clients can identify the exact business error (e.g. USER_INACTIVE).
func MapInfraToServiceError ¶
MapInfraToServiceError translates an infrastructure failure into a service-layer error, so infrastructure detail stops at the boundary. It returns nil for errors that did not come from the infrastructure layer.
func MapRepoToServiceError ¶
MapRepoToServiceError maps repository error to service error
func MapServiceToHandlerError ¶
MapServiceToHandlerError maps service error to handler error. Domain codes (6xxx) and external codes (7xxx) are preserved as-is so that clients receive the specific error code. Repo/service codes are translated to generic handler codes to hide infrastructure details.
Only Details crosses the boundary, never Message: Message is the developer message and may name a table, a host, or a driver failure, and Details is the field documented as client-facing. The original error stays reachable through Unwrap, so a log of the returned error still shows the full chain.
The returned error is always a new one. Mapping never mutates the error it was given, because a caller may hold it, log it, or map it again from another goroutine.
func MapToApplicationError ¶
MapToApplicationError converts any error into an application-layer AppError.
Domain errors keep their own code, because the business meaning is what the caller needs. Infrastructure and repository errors are translated, because "the database timed out" is not something a use case caller can act on.
func NewApplicationError ¶
NewApplicationError creates a new application-layer error. Pass "" as message to use the registered message for the code.
func NewBadRequest ¶
NewBadRequest creates a 400 Bad Request error
func NewConflict ¶
NewConflict creates a 409 Conflict error
func NewDomainError ¶
NewDomainError creates a new domain error. Pass "" as message to use the registered message for the code.
func NewForbidden ¶
NewForbidden creates a 403 Forbidden error
func NewHandlerError ¶
NewHandlerError creates a new handler error
func NewInfraError ¶
NewInfraError creates a new infrastructure-layer error. Pass "" as message to use the registered message for the code.
func NewInternalError ¶
NewInternalError creates a 500 Internal Server error
func NewNotFound ¶
NewNotFound creates a 404 Not Found error
func NewRepoError ¶
NewRepoError creates a new repository error
func NewServiceError ¶
NewServiceError creates a new service error
func NewTimeoutError ¶
NewTimeoutError creates a 504 Timeout error
func NewUnauthorized ¶
NewUnauthorized creates a 401 Unauthorized error
func NewValidationError ¶
NewValidationError creates a 400 Validation error
func RecoverFromPanic ¶
RecoverFromPanic recovers from panic and converts it to an AppError
func Split ¶
Split partitions err into the failures worth retrying and the ones that are final, so a caller can redo the recoverable half of a batch instead of redoing all of it or none of it.
func WithCaller ¶
WithCaller automatically adds caller information to error Usage: errors.WithCaller(err, 0) - will get the caller of WithCaller
func WithSource ¶
WithSource adds source file and function information to error This helps track where the error originated in the codebase
func WrapApplicationError ¶
WrapApplicationError wraps an error as an application-layer error.
func WrapBadRequest ¶
WrapBadRequest wraps an error as 400 Bad Request
func WrapConflict ¶
WrapConflict wraps an error as 409 Conflict
func WrapDomainError ¶
WrapDomainError wraps an error as a domain error.
func WrapForbidden ¶
WrapForbidden wraps an error as 403 Forbidden
func WrapHandlerError ¶
WrapHandlerError wraps an error as handler error
func WrapInfraError ¶
WrapInfraError wraps an error as an infrastructure-layer error.
func WrapInternal ¶
WrapInternal wraps an error as 500 Internal Server Error
func WrapNotFound ¶
WrapNotFound wraps an error as 404 Not Found
func WrapRepoError ¶
WrapRepoError wraps an error as repository error
func WrapServiceError ¶
WrapServiceError wraps an error as service error
func WrapUnauthorized ¶
WrapUnauthorized wraps an error as 401 Unauthorized
func (*AppError) Fingerprint ¶
Fingerprint returns a short hash identifying this error type + location. Useful for grouping identical errors.
func (*AppError) GetCategory ¶
func (e *AppError) GetCategory() ErrorCategory
GetCategory returns the category of this error
func (*AppError) GetMetadata ¶
func (e *AppError) GetMetadata() ErrorMetadata
GetMetadata returns error metadata
func (*AppError) GetSeverity ¶
func (e *AppError) GetSeverity() ErrorSeverity
GetSeverity returns the severity of this error
func (*AppError) IsRetryable ¶
IsRetryable checks if this error is retryable
func (*AppError) MarshalJSON ¶
MarshalJSON renders the error as RFC 9457 problem details.
Marshaling an AppError directly is therefore safe: the internal fields (Message, Fields, Err, Stack, Input, Output) cannot reach a client even by accident, and the payload is standards-compliant rather than a dump of Go field names. Use Problem(instance) when the occurrence URI is known.
func (*AppError) Problem ¶
Problem renders the error as RFC 9457 problem details.
instance is the URI of this specific occurrence, normally the request path; pass "" to omit it.
func (*AppError) ProblemCtx ¶
ProblemCtx is Problem with the request's context taken into account: the title is rendered in the language the context carries (see WithLanguage), and the request ID from the context, if any, becomes a request_id extension member so a client can quote one identifier back to support.
func (*AppError) WithContext ¶
WithContext enriches error with context information
func (*AppError) WithDetails ¶
WithDetails adds detailed information
func (*AppError) WithExtension ¶
WithExtension adds an RFC 9457 extension member, which is rendered as a top-level member of the problem document sent to the client.
The RFC's own members — type, title, status, detail, instance — and errorx's code and validation members cannot be overwritten this way; those keys are ignored so an extension can never rewrite the status a client branches on.
err.WithExtension("retry_after_seconds", 30)
err.WithExtension("quota", map[string]any{"limit": 1000, "remaining": 0})
Anything internal belongs in WithField instead, which never leaves the process.
func (*AppError) WithMetadata ¶
WithMetadata adds metadata to error
func (*AppError) WithOperation ¶
WithOperation adds operation name to error context
func (*AppError) WithOutput ¶
WithOutput adds output data to error
func (*AppError) WithResource ¶
WithResource adds resource information to error
func (*AppError) WithRetryAfter ¶
WithRetryAfter sets how long the client should wait before retrying, sent as the Retry-After header. Durations are rounded up to whole seconds, since the header has no finer unit; anything under a second becomes 1.
func (*AppError) WithSuggestion ¶
WithSuggestion adds a suggestion
type ChainEntry ¶
type ChainEntry struct {
Code string `json:"code"`
Message string `json:"message"`
Layer string `json:"layer"`
Timestamp time.Time `json:"timestamp"`
}
ChainEntry represents one error in a request's error chain.
type ContextKey ¶
type ContextKey string
ContextKey type for context keys
const ( ContextKeyErrorContext ContextKey = "error_context" ContextKeyUserID ContextKey = "user_id" ContextKeyRequestID ContextKey = "request_id" )
const ContextKeyLanguage ContextKey = "language"
ContextKeyLanguage carries the language a response should be rendered in.
type CustomError ¶
type CustomError = DomainCode
CustomError describes one application-defined error code and everything the registry needs to know about it. It is the same shape as DomainCode — the name is the layer-neutral one, because an application registers codes for every layer, not only the domain.
errorx.MustRegisterError(errorx.CustomError{
Code: "WALLET_INSUFFICIENT_FUNDS",
Numeric: "6001",
HTTPStatus: 409,
Severity: errorx.SeverityMedium,
Category: errorx.CategoryBusiness,
Layer: errorx.LayerDomain,
ServiceCode: errorx.ErrServiceBusinessRule,
Message: errorx.UserMessage{
En: "Your balance is too low for this transfer.",
Uz: "Balansingiz bu o'tkazma uchun yetarli emas.",
Ru: "На балансе недостаточно средств для перевода.",
},
})
err := errorx.New("WALLET_INSUFFICIENT_FUNDS", "transfer rejected")
From then on the code answers like any built-in one: GetSeverity, GetCategory, GetLayer, GetHTTPStatus, GetNumericCode, GetUserMessage, IsRetryable, and GetRetryPolicy all resolve it, and WriteProblem renders it with its registered status and localized title.
The 6xxx numeric range is left free for application codes; errorx itself uses 1xxx-5xxx and 8xxx-9xxx.
func LookupError ¶
func LookupError(code string) (CustomError, bool)
LookupError returns the registered definition of a code.
func RegisteredErrors ¶
func RegisteredErrors() []CustomError
RegisteredErrors returns every registered code, sorted by code, including the ones errorx registers for itself. It is the introspection half of the registry: an admin endpoint or a startup log can print exactly what this process will answer with.
type DomainCode ¶
type DomainCode struct {
// Code is the stable string identifier, e.g. "USER_NOT_FOUND".
Code string
// Numeric is the machine-facing numeric code returned to clients.
Numeric string
// HTTPStatus is the status the transport layer should respond with.
HTTPStatus int
Severity ErrorSeverity
Category ErrorCategory
Retry RetryPolicy
// ServiceCode is the service-layer code this maps to, e.g. ErrServiceNotFound.
ServiceCode string
// Layer is the layer the code belongs to. Leave it empty and GetLayer falls
// back to the code prefix; business codes usually want LayerDomain.
Layer ErrorLayer
// Message is the user-facing text, per language.
Message UserMessage
}
DomainCode describes one application error code and everything the registry needs to know about it. Applications own their business codes; errorx ships only the infrastructure ones (repo, service, handler, and the ./adapter external-service codes).
type DomainError ¶
DomainError is implemented by domain-layer errors that carry a machine-readable code. Domain packages satisfy it without importing errorx, which keeps the dependency arrow pointing inward.
type ErrorCategory ¶
type ErrorCategory string
ErrorCategory represents the category of an error
const ( CategoryValidation ErrorCategory = "VALIDATION" // Input validation errors CategorySecurity ErrorCategory = "SECURITY" // Authentication/Authorization errors CategoryData ErrorCategory = "DATA" // Data access/persistence errors CategoryBusiness ErrorCategory = "BUSINESS" // Business logic violations CategorySystem ErrorCategory = "SYSTEM" // System/infrastructure errors CategoryExternal ErrorCategory = "EXTERNAL" // External service errors CategoryNetwork ErrorCategory = "NETWORK" // Network/connectivity errors )
func GetCategory ¶
func GetCategory(code string) ErrorCategory
GetCategory returns the category for an error code
type ErrorChain ¶
type ErrorChain struct {
// contains filtered or unexported fields
}
ErrorChain tracks errors grouped by request_id.
func NewErrorChain ¶
func NewErrorChain(maxAge time.Duration) *ErrorChain
NewErrorChain creates a new error chain tracker.
func (*ErrorChain) Get ¶
func (c *ErrorChain) Get(requestID string) []ChainEntry
Get returns the error chain for a request_id.
func (*ErrorChain) Record ¶
func (c *ErrorChain) Record(ctx context.Context, err *AppError)
Record adds an error to the chain for the current request.
func (*ErrorChain) RecordAll ¶
func (c *ErrorChain) RecordAll(ctx context.Context, err error)
RecordAll adds every failure in err to the chain, expanding a MultiError into one entry per member. A batch that failed three ways should read as three entries, not one.
func (*ErrorChain) StartCleanup ¶
func (c *ErrorChain) StartCleanup(ctx context.Context)
StartCleanup runs periodic cleanup.
type ErrorContext ¶
type ErrorContext struct {
UserID string `json:"user_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
Operation string `json:"operation,omitempty"`
Resource string `json:"resource,omitempty"`
ResourceID string `json:"resource_id,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
Path string `json:"path,omitempty"`
Method string `json:"method,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
ErrorContext provides additional context for errors
func GetErrorContext ¶
func GetErrorContext(ctx context.Context) *ErrorContext
GetErrorContext extracts ErrorContext from context
type ErrorDefinition ¶
type ErrorDefinition struct {
Code string `json:"code"`
NumericCode string `json:"numeric_code"`
Message string `json:"message"`
Layer string `json:"layer"` // Repository, Service, Handler
Category string `json:"category"` // Data, Validation, Security, System, Business
HTTPStatus int `json:"http_status,omitempty"`
}
ErrorDefinition represents a single error definition in the system swagger:model ErrorDefinition
func GetAllErrors ¶
func GetAllErrors() []ErrorDefinition
GetAllErrors returns a list of all defined errors in the system
func GetErrorsByFilter ¶
func GetErrorsByFilter(layer, category, code string) []ErrorDefinition
GetErrorsByFilter filters errors by optional criteria
type ErrorDetailConfig ¶
type ErrorDetailConfig struct {
Message UserMessage
HTTPStatus int
}
ErrorDetailConfig represents configuration for an error code
type ErrorHook ¶
ErrorHook is a function that gets called when an error occurs
func AlertingHook ¶
AlertingHook creates a hook that sends alerts for critical errors
func LoggingHook ¶
LoggingHook creates a hook that logs errors
func MetricsHook ¶
func MetricsHook(recordFn func(code string, severity ErrorSeverity, category ErrorCategory)) ErrorHook
MetricsHook creates a hook that records metrics
type ErrorHookManager ¶
type ErrorHookManager struct {
// contains filtered or unexported fields
}
ErrorHookManager manages error hooks
func GetGlobalHookManager ¶
func GetGlobalHookManager() *ErrorHookManager
GetGlobalHookManager returns the global error hook manager
func NewErrorHookManager ¶
func NewErrorHookManager() *ErrorHookManager
NewErrorHookManager creates a new ErrorHookManager
func (*ErrorHookManager) AddHook ¶
func (m *ErrorHookManager) AddHook(hook ErrorHook)
AddHook adds an error hook
func (*ErrorHookManager) ExecuteHooks ¶
func (m *ErrorHookManager) ExecuteHooks(ctx context.Context, err *AppError)
ExecuteHooks executes all registered hooks
type ErrorLayer ¶
type ErrorLayer string
ErrorLayer represents which layer the error originated from
const ( LayerHandler ErrorLayer = "HANDLER" // HTTP/controller layer (DDD: presentation) LayerApplication ErrorLayer = "APPLICATION" // Use cases, commands, orchestration LayerService ErrorLayer = "SERVICE" // Three-layer name for the application layer LayerDomain ErrorLayer = "DOMAIN" // Entities, value objects, business rules LayerInfrastructure ErrorLayer = "INFRASTRUCTURE" // Drivers, connections, serialization, config LayerRepository ErrorLayer = "REPOSITORY" // Data access, the persistence half of infrastructure LayerExternal ErrorLayer = "EXTERNAL" // External service integration LayerSystem ErrorLayer = "SYSTEM" // Anything unclassified )
type ErrorMetadata ¶
type ErrorMetadata struct {
Severity ErrorSeverity `json:"severity"`
Category ErrorCategory `json:"category"`
Layer ErrorLayer `json:"layer"`
RetryStrategy RetryStrategy `json:"retry_strategy"`
Retryable bool `json:"retryable"`
UserVisible bool `json:"user_visible"` // Whether to show to end users
AlertOps bool `json:"alert_ops"` // Whether to alert operations team
Tags []string `json:"tags,omitempty"`
CustomData map[string]any `json:"custom_data,omitempty"`
}
ErrorMetadata contains additional metadata about an error
func GetErrorMetadata ¶
func GetErrorMetadata(code string) ErrorMetadata
GetErrorMetadata returns complete metadata for an error code
type ErrorMetrics ¶
type ErrorMetrics struct {
// contains filtered or unexported fields
}
ErrorMetrics tracks error statistics
func GetGlobalMetrics ¶
func GetGlobalMetrics() *ErrorMetrics
GetGlobalMetrics returns the global error metrics instance
func NewErrorMetrics ¶
func NewErrorMetrics() *ErrorMetrics
NewErrorMetrics creates a new ErrorMetrics instance
func (*ErrorMetrics) GetStats ¶
func (m *ErrorMetrics) GetStats() map[string]any
GetStats returns current error statistics as deep copies (safe for concurrent use).
func (*ErrorMetrics) RecordError ¶
func (m *ErrorMetrics) RecordError(err *AppError)
RecordError records an error occurrence
type ErrorSeverity ¶
type ErrorSeverity string
ErrorSeverity represents the severity level of an error
const ( SeverityCritical ErrorSeverity = "CRITICAL" // System-wide impact, immediate action required SeverityHigh ErrorSeverity = "HIGH" // Major functionality affected SeverityMedium ErrorSeverity = "MEDIUM" // Partial functionality affected SeverityLow ErrorSeverity = "LOW" // Minor issue, no significant impact SeverityInfo ErrorSeverity = "INFO" // Informational, not an actual error )
func GetSeverity ¶
func GetSeverity(code string) ErrorSeverity
GetSeverity returns the severity level for an error code
type FieldError ¶
type FieldError struct {
// Field is the input path that failed, e.g. "email" or "items[2].qty".
Field string `json:"field"`
// Code is the errorx code for this specific failure.
Code string `json:"code"`
// Message is the localized, user-facing explanation.
Message string `json:"message"`
}
FieldError is one field-level validation failure.
Unlike most of AppError, these fields ARE sent to clients: telling a caller which field is wrong is the entire point. Never put internal detail here.
func GetValidationErrors ¶
func GetValidationErrors(err error) []FieldError
GetValidationErrors returns the field failures carried by err, or nil. It looks through wrapping, so a validation error keeps its detail after being mapped up through the layers.
func (FieldError) Error ¶
func (f FieldError) Error() string
Error implements error so a single FieldError can travel on its own.
type MultiError ¶
type MultiError struct {
*AppError
// Errors holds every failure, in the order given to [Join].
Errors []error
}
MultiError carries several independent failures — a batch, a fan-out, a set of parallel calls — while still behaving like the single most serious one.
The embedded *AppError is the dominant error, so HTTPStatus, UserMsg, Type, and the metadata helpers all answer as they would for that error alone. MultiError.Unwrap exposes the full set to errors.Is and errors.As.
It is a distinct type because it has to be: a type cannot have both Unwrap() error and Unwrap() []error, and AppError already has the first.
func (*MultiError) As ¶
func (m *MultiError) As(target any) bool
As resolves *AppError targets to the dominant error.
Without this, errors.As would walk the joined list and return whichever AppError happened to come first, so GetCode and HTTPStatus would report an arbitrary member instead of the one the response is built from.
func (*MultiError) IsRetryable ¶
func (m *MultiError) IsRetryable() bool
IsRetryable reports whether the whole aggregate can be retried, which requires every member to be retryable.
Retrying a batch that contains one permanent failure just reproduces that failure, so a single fatal member makes the aggregate fatal. Use Split to retry the recoverable part instead.
func (*MultiError) Unwrap ¶
func (m *MultiError) Unwrap() []error
Unwrap exposes every joined error, which is what makes errors.Is and errors.As search all of them.
type Problem ¶
type Problem struct {
// Type is a URI identifying the problem type. It is "about:blank" until
// SetProblemBaseURI names a base, which is what the RFC prescribes for a
// problem with no dereferenceable documentation.
Type string `json:"type"`
// Title is a short, human-readable summary of the problem type. It is the
// localized user message, never the internal developer message.
Title string `json:"title"`
// Status is the HTTP status code, repeated here for consumers that only
// have the body. It always matches the response's status line.
Status int `json:"status"`
// Detail explains this specific occurrence. It carries AppError.Details,
// which is written for the client; AppError.Message is internal and is
// never used here.
Detail string `json:"detail,omitempty"`
// Instance is a URI identifying this specific occurrence, typically the
// request path.
Instance string `json:"instance,omitempty"`
// Code is the stable errorx code, e.g. "HANDLER_NOT_FOUND". Clients branch
// on this rather than on the type URI or the status.
Code string `json:"code,omitempty"`
// NumericCode is the same failure as a number, e.g. 4041 — the registry's
// numeric code for Code. It is a JSON number rather than a string, so a
// client can switch on it or range over a block without parsing, and it is
// omitted rather than sent as a string when a code's registered numeric is
// not an integer. ValidateRegistry rejects that case at startup, so in a
// validated registry it is always present.
NumericCode int `json:"numeric_code,omitempty"`
// Retryable says whether repeating the request can succeed, as the code's
// registered retry policy defines it. It is the most actionable member in
// the document: without it a client guesses from the status, and the status
// does not know — one 500 is a transient deadlock, the next is a nil map.
//
// It is present only when true, so its absence means "do not retry". A
// client that sees it should still honor Retry-After, which carries the
// delay for the same failure.
Retryable bool `json:"retryable,omitempty"`
// Validation lists the field-level failures behind a validation error.
Validation []FieldError `json:"validation,omitempty"`
// Extensions are the remaining extension members. They are flattened into
// the document's top level on the wire — RFC 9457 §3.2 places extensions
// beside the standard members, not in a nested object — and a key that
// collides with a standard member is dropped rather than allowed to
// overwrite it.
Extensions map[string]any `json:"-"`
}
Problem is the RFC 9457 (Problem Details for HTTP APIs) representation of an AppError — the only shape of an AppError that is ever safe to send to a client.
It exists so the wire format is decoupled from the internal struct: renaming an AppError field must never change what clients parse, and an internal field added later must never leak by default. Type, Title, Status, Detail, and Instance are the RFC's own members; Code and Validation are extension members, which RFC 9457 §3.2 explicitly permits.
func (Problem) MarshalJSON ¶
MarshalJSON renders the problem with its extension members flattened into the top level, as RFC 9457 §3.2 requires.
The standard members keep their declared order and the extensions follow in sorted order, so the same problem always produces the same bytes. JSON itself does not care, but a documented example, a golden-file test, and an HTTP cache key all do.
func (*Problem) UnmarshalJSON ¶
UnmarshalJSON parses a problem document, collecting every member that is not a standard one into Extensions. It is the inverse of MarshalJSON, so a client built on errorx reads back exactly what a server on errorx sent.
type RateMonitor ¶
type RateMonitor struct {
// contains filtered or unexported fields
}
RateMonitor tracks error rates per code using a sliding window.
func NewRateMonitor ¶
func NewRateMonitor(cfg RateMonitorConfig) *RateMonitor
NewRateMonitor creates a new rate monitor.
func (*RateMonitor) Cleanup ¶
func (m *RateMonitor) Cleanup()
Cleanup removes expired windows to prevent memory leaks.
func (*RateMonitor) Record ¶
func (m *RateMonitor) Record(code string)
Record records an error occurrence and checks the threshold.
func (*RateMonitor) StartCleanup ¶
func (m *RateMonitor) StartCleanup(ctx context.Context)
StartCleanup runs periodic cleanup in background. Call cancel to stop.
type RateMonitorConfig ¶
type RateMonitorConfig struct {
Window time.Duration
Threshold int
OnBreach func(code string, count int)
}
RateMonitorConfig configures the error rate monitor.
type RegistryProblem ¶
type RegistryProblem struct {
// Code is the error code the problem concerns.
Code string
// Problem describes what is wrong, in one sentence.
Problem string
}
RegistryProblem is one thing wrong with the registry.
func ValidateRegistry ¶
func ValidateRegistry() []RegistryProblem
ValidateRegistry checks every registered code for the mistakes that are invisible at registration time and expensive later: two codes sharing one numeric code, a missing HTTP status, an untranslated message, a retry policy that contradicts itself.
Call it from a test, or at startup after registering application codes. The registry is a table nobody reads once it passes a few dozen entries, and a duplicate numeric code is the kind of thing that surfaces as a client branching on the wrong error months later.
It returns nil when everything checks out.
func (RegistryProblem) String ¶
func (p RegistryProblem) String() string
type ResolutionAction ¶
ResolutionAction is a function that attempts to resolve/mitigate an error. Returns true if the resolution was applied.
type Resolver ¶
type Resolver struct {
// contains filtered or unexported fields
}
Resolver maps error codes to automatic resolution actions.
func (*Resolver) Register ¶
func (r *Resolver) Register(code string, action ResolutionAction)
Register adds a resolution action for an error code.
type RetryConfig ¶
type RetryConfig struct {
MaxAttempts int // Maximum number of retry attempts
InitialDelay time.Duration // Initial delay before first retry
MaxDelay time.Duration // Maximum delay between retries
Multiplier float64 // Multiplier for exponential backoff
ShouldRetry func(error) bool // Custom function to determine if error is retryable
}
RetryConfig configures retry behavior
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns default retry configuration
type RetryPolicy ¶
RetryPolicy defines retry behavior for an error code.
func GetRetryPolicy ¶
func GetRetryPolicy(code string) RetryPolicy
GetRetryPolicy returns retry policy for an error code.
type RetryStrategy ¶
type RetryStrategy string
RetryStrategy defines how an error should be handled for retries
const ( RetryNever RetryStrategy = "NEVER" // Never retry this error RetryStrategyImmediate RetryStrategy = "IMMEDIATE" // Retry immediately RetryStrategyExponential RetryStrategy = "EXPONENTIAL" // Retry with exponential backoff RetryStrategyLinear RetryStrategy = "LINEAR" // Retry with linear backoff )
func GetRetryStrategy ¶
func GetRetryStrategy(code string) RetryStrategy
GetRetryStrategy returns the retry strategy for an error code
type SLOConfig ¶
type SLOConfig struct {
Target float64 // target success rate (e.g., 0.999 = 99.9%)
Window time.Duration // measurement window (e.g., 1 hour)
OnBudgetExhausted func(stats SLOStats) // called when error budget is exhausted
}
SLOConfig configures the SLO tracker.
type SLOStats ¶
type SLOStats struct {
TotalRequests int64 `json:"total_requests"`
ErrorRequests int64 `json:"error_requests"`
SuccessRate float64 `json:"success_rate"`
Target float64 `json:"target"`
BudgetTotal int64 `json:"budget_total"` // max allowed errors
BudgetUsed int64 `json:"budget_used"` // errors so far
BudgetRemaining int64 `json:"budget_remaining"`
Exhausted bool `json:"exhausted"`
WindowStart string `json:"window_start"`
}
SLOStats holds current SLO statistics.
type SLOTracker ¶
type SLOTracker struct {
// contains filtered or unexported fields
}
SLOTracker tracks error budget based on success rate target.
func NewSLOTracker ¶
func NewSLOTracker(cfg SLOConfig) *SLOTracker
NewSLOTracker creates a new SLO tracker.
func (*SLOTracker) RecordError ¶
func (s *SLOTracker) RecordError()
RecordError records a failed request.
func (*SLOTracker) RecordSuccess ¶
func (s *SLOTracker) RecordSuccess()
RecordSuccess records a successful request.
func (*SLOTracker) Stats ¶
func (s *SLOTracker) Stats() SLOStats
Stats returns current SLO statistics.
type Sampler ¶
type Sampler struct {
// contains filtered or unexported fields
}
Sampler decides whether to log/report an error based on rate. Under threshold: log everything. Over threshold: log every Nth.
func NewSampler ¶
func NewSampler(cfg SamplerConfig) *Sampler
NewSampler creates a new error sampler.
type SamplerConfig ¶
type SamplerConfig struct {
Window time.Duration // sampling window (default: 1 minute)
Threshold int // after this many errors per code, start sampling (default: 100)
SampleRate int // log every Nth error when sampling (default: 10)
}
SamplerConfig configures error log sampling.
type UserMessage ¶
type UserMessage struct {
En string `json:"en"` // English
Uz string `json:"uz"` // Uzbek
Ru string `json:"ru"` // Russian
}
UserMessage represents a user-friendly error message with i18n support
type ValidationBuilder ¶
type ValidationBuilder struct {
// contains filtered or unexported fields
}
ValidationBuilder collects field failures so a request can be rejected once with every problem listed, instead of one round trip per mistake.
The zero value is not usable; call NewValidation. A builder is not safe for concurrent use — validate on one goroutine.
func NewValidation ¶
func NewValidation() *ValidationBuilder
NewValidation returns an empty validation builder.
func (*ValidationBuilder) Add ¶
func (v *ValidationBuilder) Add(field, code, message string) *ValidationBuilder
Add records a failure for field. An empty message is resolved from the registry for code, so callers can lean on the codes they already registered.
func (*ValidationBuilder) AddErr ¶
func (v *ValidationBuilder) AddErr(field string, err error) *ValidationBuilder
AddErr records err as a failure for field, reusing err's code and user message when it is an AppError.
func (*ValidationBuilder) Err ¶
func (v *ValidationBuilder) Err() *AppError
Err returns the collected failures as a single AppError, or nil if nothing failed — so `if err := v.Err(); err != nil` is the whole calling convention.
The result is an ordinary ErrValidation AppError with its Validation slice populated, which means every existing handler, hook, and reporter treats it like any other error.
func (*ValidationBuilder) Fields ¶
func (v *ValidationBuilder) Fields() []FieldError
Fields returns a copy of the collected failures.
func (*ValidationBuilder) HasErrors ¶
func (v *ValidationBuilder) HasErrors() bool
HasErrors reports whether anything failed.
func (*ValidationBuilder) Len ¶
func (v *ValidationBuilder) Len() int
Len reports how many failures have been collected.
func (*ValidationBuilder) WithLang ¶
func (v *ValidationBuilder) WithLang(lang string) *ValidationBuilder
WithLang sets the language used to resolve registry messages for codes added without explicit text. It defaults to English.
Source Files
¶
- application.go
- chain.go
- codes.go
- codes_broker.go
- codes_domain.go
- codes_external.go
- context.go
- custom.go
- doc.go
- domain.go
- errors.go
- factory.go
- handler.go
- infrastructure.go
- language.go
- logging.go
- messages.go
- metrics.go
- multierror.go
- problem.go
- rate_monitor.go
- registry.go
- repository.go
- resolver.go
- respond.go
- retry.go
- sampling.go
- service.go
- slo.go
- test_errors.go
- types.go
- validate.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package adapter holds the machinery every driver adapter under ./adapter shares: classify the driver's error into an errorx code, then build the AppError the same way every time.
|
Package adapter holds the machinery every driver adapter under ./adapter shares: classify the driver's error into an errorx code, then build the AppError the same way every time. |
|
adaptertest
Package adaptertest is the conformance suite every driver adapter runs against.
|
Package adaptertest is the conformance suite every driver adapter runs against. |
|
asynq
Package asynq converts task-queue failures into an errorx.AppError.
|
Package asynq converts task-queue failures into an errorx.AppError. |
|
clickhouse
Package clickhouse converts clickhouse-go failures into an errorx.AppError.
|
Package clickhouse converts clickhouse-go failures into an errorx.AppError. |
|
eventbus
Package eventbus converts publish/subscribe failures into an errorx.AppError.
|
Package eventbus converts publish/subscribe failures into an errorx.AppError. |
|
firebase
Package firebase converts Firebase Cloud Messaging failures into an errorx.AppError.
|
Package firebase converts Firebase Cloud Messaging failures into an errorx.AppError. |
|
kafka
Package kafka converts segmentio/kafka-go failures into an errorx.AppError.
|
Package kafka converts segmentio/kafka-go failures into an errorx.AppError. |
|
minio
Package minio converts MinIO object-storage failures into an errorx.AppError.
|
Package minio converts MinIO object-storage failures into an errorx.AppError. |
|
mongo
Package mongo converts mongo-driver failures into an errorx.AppError.
|
Package mongo converts mongo-driver failures into an errorx.AppError. |
|
mysql
Package mysql converts go-sql-driver/mysql failures into an errorx.AppError.
|
Package mysql converts go-sql-driver/mysql failures into an errorx.AppError. |
|
nats
Package nats converts nats.go and JetStream failures into an errorx.AppError.
|
Package nats converts nats.go and JetStream failures into an errorx.AppError. |
|
postgres
Package errors contains PostgreSQL error codes constants.
|
Package errors contains PostgreSQL error codes constants. |
|
rabbitmq
Package rabbitmq converts amqp091-go failures into an errorx.AppError.
|
Package rabbitmq converts amqp091-go failures into an errorx.AppError. |
|
redis
Package redis converts go-redis failures into an errorx.AppError.
|
Package redis converts go-redis failures into an errorx.AppError. |
|
sql
Package sql converts database/sql failures into an errorx.AppError without depending on any driver.
|
Package sql converts database/sql failures into an errorx.AppError without depending on any driver. |
|
telegram
Package telegram converts Telegram Bot API failures into an errorx.AppError.
|
Package telegram converts Telegram Bot API failures into an errorx.AppError. |
|
Package contextx carries request-scoped correlation values through context.Context using unexported key types so they cannot collide with keys from other packages.
|
Package contextx carries request-scoped correlation values through context.Context using unexported key types so they cannot collide with keys from other packages. |
|
Package logger defines the small logging interface the errorx sub-packages depend on, so they bind to your logger rather than shipping one.
|
Package logger defines the small logging interface the errorx sub-packages depend on, so they bind to your logger rather than shipping one. |
|
Package logwriter persists errors to a repository, with front ends for the HTTP and service layers.
|
Package logwriter persists errors to a repository, with front ends for the HTTP and service layers. |
|
reporter
|
|
|
alerter
Package alerter delivers error alerts through a task queue, debounced per error code so one failing code cannot flood the channel.
|
Package alerter delivers error alerts through a task queue, debounced per error code so one failing code cannot flood the channel. |
|
webhook
Package webhook delivers error alerts to a webhook endpoint such as Slack, Discord, or PagerDuty, buffering through Redis so delivery never blocks a request.
|
Package webhook delivers error alerts to a webhook endpoint such as Slack, Discord, or PagerDuty, buffering through Redis so delivery never blocks a request. |