errorx

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: MIT Imports: 20 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

errorx

Structured errors for Go services: one error type that carries a stable code, an HTTP status, a localized user message, and structured fields — plus a registry that tells you how to treat any code, driver adapters that normalize third-party failures into it, and hooks for metrics, alerting, and retries.

go get github.com/bakhod1r/errorx

Quick start

import "github.com/bakhod1r/errorx"

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) // RFC 9457 problem details
}

AppError wraps the original error, so errors.Is and errors.As keep working across every layer.

The registry

Every code is registered once with its severity, category, layer, retry policy, HTTP status, and per-language message. Given a code alone the registry answers how to treat it:

errorx.GetSeverity(code)      // SeverityLow … SeverityCritical
errorx.GetCategory(code)      // CategoryData, CategorySecurity, CategoryExternal, …
errorx.GetLayer(code)         // repo / service / handler
errorx.IsRetryable(code)      // drives RetryWithBackoff
errorx.GetRetryPolicy(code)   // attempts + backoff for this code
errorx.ShouldAlertOps(code)   // page a human, or not
errorx.GetHTTPStatus(code)    // transport status
errorx.GetNumericCode(code)   // machine-facing numeric code

errorx ships only infrastructure codes (repository, service, handler, and the external-service codes used by ./adapter). Business codes belong to your application — register them at startup:

func init() {
	errorx.MustRegisterErrors(
		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.",
				Uz: "Foydalanuvchi topilmadi.",
				Ru: "Пользователь не найден.",
			},
		},
	)
}

A registered code is then indistinguishable from a built-in one: New and Wrap resolve its status, severity, category, layer and localized message, and WriteProblem renders it — the developer message stays internal as always.

err := errorx.New("USER_NOT_FOUND", "lookup by id 42 returned no rows")
errorx.WriteProblemRequest(w, r, err) // 404, localized title, numeric_code 6001
Function Purpose
RegisterError(c) error Register one code; returns what is wrong with the definition.
RegisterErrors(...) error Register a batch atomically — one bad definition registers none of them.
MustRegisterError / MustRegisterErrors The same, panicking, for init.
UnregisterError(code) Remove a code completely (numeric, metadata, message, status).
IsRegistered(code) / LookupError(code) Ask whether, and with what, a code is registered.
RegisteredErrors() Every registered code, sorted — for an admin endpoint or a startup log.

A definition is rejected rather than half-applied: an empty code, a numeric code that is not an integer or is already claimed by another code, a missing English message, an impossible HTTP status, or a retry policy that contradicts itself. Zero fields default to status 500, SeverityMedium, CategorySystem, and the layer implied by the code prefix. The 6xxx numeric range is left free for application codes.

RegisterDomainCode and RegisterDomainCodes remain as the older names for the same table; they do not validate.

Registration is safe to call concurrently with error construction, so a plugin or a config reload can add codes to a running process — startup is still the sane place for it.

Once everything is registered, check the table mechanically:

if err := errorx.ValidateRegistryErr(); err != nil {
	log.Fatal(err) // duplicate numeric codes, missing statuses or translations,
}                  // retry policies that contradict themselves

Nobody re-reads a registry past a few dozen entries, and a numeric code claimed by two errors surfaces months later as a client branching on the wrong one.

Layer mapping

Errors are translated as they cross a boundary rather than leaked upward. Each layer has the same three pieces — its own code set, a New/Wrap pair, and a mapper into the next layer:

Layer Codes Create / wrap Map upward
Domain (entities, rules) DOMAIN_* (8xxx) NewDomainError, WrapDomainError MapDomainToServiceError
Infrastructure (drivers, IO, config) INFRA_* (91xx) NewInfraError, WrapInfraError MapInfraToServiceError
Repository (persistence) REPO_* (2xxx) NewRepoError, WrapRepoError MapRepoToServiceError
Application (use cases) APP_* (90xx) NewApplicationError, WrapApplicationError MapServiceToHandlerError
Service (three-layer name for the same) SERVICE_* (3xxx) NewServiceError, WrapServiceError MapServiceToHandlerError
Handler (transport, DDD: presentation) HANDLER_* (4xxx/5xxx) NewHandlerError, WrapHandlerError WriteProblem, MapToHTTPStatus

Both vocabularies work: a three-layer clean architecture uses handler / service / repository, a DDD codebase uses presentation / application / domain / infrastructure, and GetLayer(code) reports the right layer either way.

MapToServiceError and MapToApplicationError are the catch-alls: give either one a domain, infrastructure, repository, or raw error and it returns the right AppError for that layer.

// domain layer — an entity refuses the operation
func (o *Order) Ship() error {
	if o.status == statusCancelled {
		return errorx.NewDomainError(errorx.ErrDomainInvalidState, "cannot ship a cancelled order")
	}
	...
}

// infrastructure layer — a mechanism failed
if err := conn.Ping(ctx); err != nil {
	return errorx.WrapInfraError(err, errorx.ErrInfraConnection, "")
}

// application layer
if err := order.Ship(); err != nil {
	return errorx.MapToApplicationError(err)
}

// handler layer
appErr := errorx.MapServiceToHandlerError(err)
errorx.WriteProblem(w, appErr, r.URL.Path)

Two rules hold at every boundary. Only Details crosses it — Message is the developer message and may name a table, a host, or a driver failure, so it stays behind while the original error remains reachable through Unwrap for the logs. And mapping never mutates its input: a mapper that has to change a status returns a copy, because the caller may still be holding, logging, or re-mapping the error it passed in.

Two rules govern the handoff:

  • Business meaning travels. A DOMAIN_* or APP_* code reaches the handler intact, with its registered status and user message, because the client can act on it.
  • Mechanism does not. An INFRA_* or REPO_* code is always translated at the boundary — the client gets HANDLER_SERVICE_UNAVAILABLE, never "connection pool exhausted". The original error stays in the chain, so errors.Is and your logs keep the full detail.

The HTTP response

Success and failure are written by the same package, so a handler never hand-rolls either half:

func getUser(w http.ResponseWriter, r *http.Request) {
	user, err := svc.GetUser(r.Context(), id)
	if err != nil {
		log.Error(err)                          // full internal detail
		errorx.WriteProblem(w, err, r.URL.Path) // vetted client detail
		return
	}
	errorx.WriteOK(w, user)
}
Outcome Call Status Content-Type
read WriteOK(w, payload) 200 application/json; charset=utf-8
create WriteCreated(w, location, payload) 201 + Location application/json; charset=utf-8
delete, empty update WriteNoContent(w) 204 —
any status WriteJSON(w, status, payload) yours application/json; charset=utf-8
failure WriteProblem(w, err, instance) from the code application/problem+json
failure, with request WriteProblemRequest(w, r, err) from the code application/problem+json
either WriteResult(w, status, payload, err, instance) whichever applies whichever applies
either, with request WriteResultRequest(w, r, status, payload, err) whichever applies whichever applies

The Request variants read the context, the instance, and the client's Accept-Language off *http.Request, which makes the handler's exit one line:

user, err := svc.GetUser(r.Context(), id)
return errorx.WriteResultRequest(w, r, http.StatusOK, user, err)

A success response is the resource itself:

{"id":42,"email":"a@example.com"}

No {"data": ...} envelope. A wrapper is a convention, not a standard, and it makes every client unwrap a level before reaching what it asked for. The error path is different precisely because it has a standard.

WriteResult collapses the handler's exit to one line that cannot send a body and an error, or neither:

return errorx.WriteResult(w, http.StatusOK, user, err, r.URL.Path)

A nil payload — including a nil *User — writes 204 rather than a body of null, and a payload that fails to encode leaves the response untouched — status and headers unwritten — so the handler can still fall back to WriteProblem. A nil slice or map is the other case: it means none, not nothing, so it is written as [] or {} and the client iterates it without a null check.

Failures

WriteProblem is the whole error story: it writes the status, the application/problem+json content type, and a body that follows RFC 9457, the IETF standard for HTTP error payloads.

{
  "type": "https://errors.example.com/handler-not-found",
  "title": "Resource not found",
  "status": 404,
  "detail": "user 42 does not exist",
  "instance": "/api/v1/users/42",
  "code": "HANDLER_NOT_FOUND",
  "numeric_code": 4004
}

type, title, status, detail, and instance are the RFC's own members. code, numeric_code, and validation are extension members, which RFC 9457 §3.2 permits.

The response names the failure three times, and each name is for a different reader:

Member For Why
status transport The coarse category — retry, re-auth, give up. Shared by many failures.
code people Stable, greppable, readable in a bug report. What clients branch on.
numeric_code machines A JSON number, so a client switches on it or ranges over a block without parsing. Registry-assigned, unique.
retryable the client's next move Whether repeating the request can succeed. Present only when true.

numeric_code is a number rather than a string: a client that has switched on 4004 must never be handed "4004" instead. A code whose registered numeric is not an integer has the member omitted rather than changing type mid-flight, and ValidateRegistryErr rejects such a code at startup so that case never ships.

The type URI comes from SetProblemBaseURI("https://errors.example.com/"), called once at startup: the code HANDLER_NOT_FOUND becomes .../handler-not-found. Without a base every problem reports the RFC's about:blank, which is correct rather than a placeholder. SetProblemLanguage picks the language for title when the error carries no UserMsg of its own.

Retries

The registry already knows which codes are worth repeating — it is the same table RetryWithBackoff reads on the server. The response passes that on rather than leaving the client to guess from a status that does not know: one 500 is a transient deadlock, the next is a nil map.

HTTP/1.1 504 Gateway Timeout
Retry-After: 10
{
  "type": "https://errors.example.com/timeout",
  "title": "Request timeout",
  "status": 504,
  "detail": "Upstream did not answer in time.",
  "instance": "/v1/reports/7",
  "code": "TIMEOUT",
  "numeric_code": 1020,
  "retryable": true
}

retryable appears only when true, so its absence means do not retry. Retry-After carries the delay from the same policy, so the header and the body cannot disagree. The status does not gate either one: a 504 the registry calls retryable earns a delay as much as a 503 does.

WithRetryAfter overrides the policy for one error — a rate limiter that knows the real window, say:

errorx.New(errorx.ErrHandlerTooManyRequests, "monthly quota exhausted").
	WithRetryAfter(30 * time.Second).
	WithExtension("quota_limit", 1000).
	WithExtension("quota_remaining", 0)

Every problem response also carries X-Content-Type-Options: nosniff, as does every success response: the body holds values the client supplied, and a browser must not re-type it as HTML.

Extension members

Anything that belongs to the client but has no RFC member of its own goes in an extension, rendered at the top level of the document as RFC 9457 §3.2 requires — never nested, never able to overwrite a standard member:

{
  "type": "about:blank",
  "title": "Too many requests",
  "status": 429,
  "code": "HANDLER_TOO_MANY_REQUESTS",
  "quota_limit": 1000,
  "quota_remaining": 0
}

WithExtension is public by definition; WithField is the internal channel and never leaves the process. Problem round-trips through encoding/json, so a client built on errorx reads back what a server on errorx sent, extensions included.

Per-request localization and correlation

SetProblemLanguage picks a default for the process. One request at a time is the context's job:

ctx := errorx.WithLanguage(r.Context(), errorx.NegotiateLanguage(r.Header.Get("Accept-Language")))
errorx.WriteProblemCtx(ctx, w, err, r.URL.Path)

NegotiateLanguage honors q-values and matches a subtag to its base language, so uz-UZ selects uz and an unsupported language falls back to the default rather than to an untranslated response. WriteProblemRequest does all of this from the request itself.

The context variants also echo the request ID — whatever GetErrorContext finds — as a request_id member, so the client quotes one identifier and the logs already have it. That holds even for an error that never passed through errorx: its text is still dropped, but the response stays correlatable.

Two safety properties hold by construction:

  • json.Marshal(appErr) produces the same problem details. AppError implements MarshalJSON, so Message, Fields, Err, Stack, Input, and Output cannot reach a client even if the error is encoded by accident.
  • A plain error becomes an opaque 500. An error that never passed through errorx has not been vetted for what it exposes, so WriteProblem sends INTERNAL_ERROR and drops the text. Log it first — that is where "connection refused on 10.0.0.7:5432" belongs.

appErr.Problem(instance) returns the struct without writing it, for servers that own their own encoding.

IsDomainError(err) and IsInfraError(err) answer the question that decides almost every branch: business rule failure, or broken mechanism?

Domain packages need not import errorx at all — a type satisfies errorx.DomainError just by having Error() string and Code() string, and MapDomainToServiceError accepts it. Register that type's codes with RegisterDomainCode(..., Layer: errorx.LayerDomain) so the registry classifies them correctly even without a DOMAIN_ prefix.

Multiple failures

A request that is wrong in several places should be rejected once, not once per mistake. NewValidation collects field failures and returns them as a single AppError:

v := errorx.NewValidation()
v.Add("email", errorx.ErrValidation, "must be an email address")
v.Add("age", errorx.ErrInvalidInput, "must be at least 18")
if err := v.Err(); err != nil { // nil when nothing failed
	return err
}

The result is an ordinary VALIDATION_ERROR, so every existing handler, hook, and reporter already knows what to do with it. The field list rides along in AppError.Validation, which — unlike Fields — is serialized into the problem details, because naming the offending field is the whole point:

{"type":"about:blank","title":"Invalid input","status":400,"code":"VALIDATION_ERROR",
 "validation":[{"field":"email","code":"VALIDATION_ERROR","message":"must be an email address"}]}

Independent operations that failed independently are a different problem, and get Join:

err := errorx.Join(saveUser(ctx), notify(ctx), index(ctx)) // nils dropped

Join returns nil if everything succeeded and the error itself if exactly one thing failed — a single failure never becomes an aggregate. Otherwise it returns a *MultiError that behaves like the most serious member (highest severity, then highest HTTP status) while errors.Is and errors.As still reach every one of them:

errorx.GetCode(err)                       // the dominant code
errorx.Is(err, errorx.ErrRepoDatabase)    // dominant only
errorx.HasCode(err, errorx.ErrValidation) // anywhere in the set
errorx.AllCodes(err)                      // every distinct code
retryable, fatal := errorx.Split(err)     // redo half a batch, not all of it

A MultiError is retryable only when every member is: retrying a batch that contains one permanent failure just reproduces it. Use Split to retry the recoverable part.

For counting, use RecordGlobal rather than RecordErrorGlobal — it expands an aggregate so fifty failures are not recorded as one:

errorx.RecordGlobal(ctx, err)
chain.RecordAll(ctx, err)

Packages

Import path What it is
errorx AppError, the code registry, layer mapping, hooks, metrics, retries
errorx/adapter the shared Spec/Classification machinery adapters are built on
errorx/adapter/postgres pgx errors → AppError, plus SQLSTATE predicates
errorx/adapter/mysql MySQL errors → AppError, by server error number
errorx/adapter/mongo MongoDB errors → AppError, by server code and error label
errorx/adapter/clickhouse ClickHouse exceptions → AppError
errorx/adapter/sql driver-agnostic database/sql fallback
errorx/adapter/redis go-redis errors → AppError
errorx/adapter/minio MinIO errors → AppError
errorx/adapter/kafka kafka-go errors → AppError, by protocol error code
errorx/adapter/rabbitmq amqp091-go errors → AppError, by AMQP reply code
errorx/adapter/nats NATS and JetStream errors → AppError
errorx/adapter/asynq task-queue errors → AppError
errorx/adapter/firebase FCM errors → AppError
errorx/adapter/telegram Telegram API errors → AppError
errorx/adapter/eventbus pub/sub errors → AppError
errorx/adapter/adaptertest the conformance suite every adapter is tested against
errorx/reporter/webhook delivers alerts to Slack/Discord/PagerDuty
errorx/reporter/alerter async, per-code debounced alerting via a task queue
errorx/logwriter persists errors, with HTTP and service-layer front ends
errorx/logger the small Log interface the sub-packages depend on
errorx/contextx request-scoped correlation values (request ID, user, IP)

Only the root package is dependency-light: each adapter pulls in its own driver and nothing else, so importing errorx alone never drags in pgx or MinIO.

Every adapter exposes the same entry point:

import pgx "github.com/bakhod1r/errorx/adapter/postgres"

if err := row.Scan(&u.ID); err != nil {
	return pgx.HandleError(err, "users", map[string]any{"user_id": id})
}
Which codes an adapter produces

What the adapter talks to decides the code family:

  • A store you own — Postgres, MySQL, Mongo, ClickHouse, Redis, MinIO — classifies into REPO_*, so MapRepoToServiceError translates it upward like any other repository error.
  • Somebody else's service — Kafka, RabbitMQ, NATS, Firebase, Telegram — classifies into EXT_*.

Classification is driven by the driver's own typed errors: a Kafka protocol code, an AMQP reply code, a MySQL error number, a Mongo error label. None of the adapters match on error text, because message wording is not part of a driver's compatibility promise.

Two properties every adapter guarantees, enforced by adapter/adaptertest:

  • The original error stays wrapped, so errors.Is still reaches the driver's own sentinels.
  • The driver's error text never lands in Details, which is serialized to clients. A MySQL duplicate-key message quotes the colliding value and an auth failure quotes the user name, so that text goes to Fields["driver_error"], which is not serialized.

Retryability comes from the registry, not from the adapter, and the distinction it encodes is the one that matters: a Kafka rebalance and a MySQL deadlock are retried, a missing topic and a RabbitMQ NO_ROUTE are not — retrying those only spends the backoff budget before surfacing a configuration fault.

Writing your own adapter
var spec = adapter.Spec{
	ResourceKey: "topic",
	Classify:    []adapter.ClassifyFunc{classifyProtocol, classifyNetwork},
	Fallback:    adapter.Classification{Code: errorx.ErrExtKafkaUnknown, Message: "..."},
}

func HandleError(err error, topic string, extra map[string]any) *errorx.AppError {
	return spec.Handle(err, topic, extra)
}

Then run it against the shared suite, which checks classification, retry verdicts, the wrapped chain, field handling, and the source frame:

adaptertest.Run(t, adaptertest.Suite{Handle: HandleError, ResourceKey: "topic", ...})

Observability

errorx.GetGlobalHookManager().AddHook(errorx.LoggingHook(zapLogger))
errorx.GetGlobalHookManager().AddHook(errorx.AlertingHook(notify))
errorx.RecordErrorGlobal(ctx, appErr)

ErrorMetrics counts by code, severity, and category. 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

Retries are driven by the registry, so only codes whose policy allows it are retried:

err := errorx.RetryWithBackoff(ctx, errorx.DefaultRetryConfig(), func() error {
	return client.Call(ctx)
})

SafeExecute turns a panic into an AppError via RecoverFromPanic.

Development

make test   # go test -race ./...
make cover  # coverage report
make lint   # golangci-lint

License

MIT — see LICENSE.

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:

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

Examples

Constants

View Source
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.
	ErrAppUnauthorized  = "APP_UNAUTHORIZED"
	CodeAppUnauthorized = "9004"

	// 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.

View Source
const (
	// 400 - Bad Request
	ErrBadRequest  = "BAD_REQUEST"
	CodeBadRequest = "1001"

	ErrInvalidInput  = "INVALID_INPUT"
	CodeInvalidInput = "1002"

	ErrValidation  = "VALIDATION_ERROR"
	CodeValidation = "1003"

	// 401 - Unauthorized
	ErrUnauthorized  = "UNAUTHORIZED"
	CodeUnauthorized = "1004"

	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"
)
View Source
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

View Source
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

View Source
const (
	ErrExtFirebaseSendFailed  = "EXT_FIREBASE_SEND_FAILED"
	CodeExtFirebaseSendFailed = "7001"

	ErrExtFirebaseInvalidToken  = "EXT_FIREBASE_INVALID_TOKEN"
	CodeExtFirebaseInvalidToken = "7002"

	ErrExtFirebaseQuotaExceeded  = "EXT_FIREBASE_QUOTA_EXCEEDED"
	CodeExtFirebaseQuotaExceeded = "7003"

	ErrExtFirebaseUnavailable  = "EXT_FIREBASE_UNAVAILABLE"
	CodeExtFirebaseUnavailable = "7004"
)

External Firebase error codes

View Source
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

View Source
const (
	ErrExtKafkaConnection  = "EXT_KAFKA_CONNECTION"
	CodeExtKafkaConnection = "7041"

	ErrExtKafkaUnavailable  = "EXT_KAFKA_UNAVAILABLE"
	CodeExtKafkaUnavailable = "7042"

	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

View Source
const (
	ErrExtRabbitConnection  = "EXT_RABBIT_CONNECTION"
	CodeExtRabbitConnection = "7051"

	ErrExtRabbitUnavailable  = "EXT_RABBIT_UNAVAILABLE"
	CodeExtRabbitUnavailable = "7052"

	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

View Source
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

View Source
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.

View Source
const (
	// HTTP handler errors
	ErrHandlerBadRequest  = "HANDLER_BAD_REQUEST"
	CodeHandlerBadRequest = "4000"

	ErrHandlerUnauthorized  = "HANDLER_UNAUTHORIZED"
	CodeHandlerUnauthorized = "4001"

	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"

	ErrHandlerServiceUnavailable  = "HANDLER_SERVICE_UNAVAILABLE"
	CodeHandlerServiceUnavailable = "5003"

	ErrHandlerInternal  = "HANDLER_INTERNAL_ERROR"
	CodeHandlerInternal = "5000"

	ErrHandlerUnknown  = "HANDLER_UNKNOWN_ERROR"
	CodeHandlerUnknown = "5099"
)
View Source
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.
	ErrInfraUnavailable  = "INFRA_UNAVAILABLE"
	CodeInfraUnavailable = "9103"

	// 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.

View Source
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.
	ErrRepoUnavailable  = "REPO_UNAVAILABLE"
	CodeRepoUnavailable = "2009"

	// 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.
	ErrRepoUnauthorized  = "REPO_UNAUTHORIZED"
	CodeRepoUnauthorized = "2012"

	ErrRepoUnknown  = "REPO_UNKNOWN_ERROR"
	CodeRepoUnknown = "2099"
)
View Source
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"

	ErrServiceUnauthorized  = "SERVICE_UNAUTHORIZED"
	CodeServiceUnauthorized = "3005"

	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"
)
View Source
const JSONMediaType = "application/json; charset=utf-8"

JSONMediaType is the media type for successful JSON responses. Errors use ProblemMediaType instead.

View Source
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

View Source
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.

View Source
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 AllCodes

func AllCodes(err error) []string

AllCodes returns the code of every error in err, de-duplicated, in order.

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

func GetCaller(skip int) (file, function string)

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 GetCode

func GetCode(err error) string

GetCode returns error code from error

func GetDomainNumericCode

func GetDomainNumericCode(code string) string

GetDomainNumericCode returns numeric code for a domain error code, or empty string.

func GetDomainServiceCode

func GetDomainServiceCode(code string) string

GetDomainServiceCode returns the service error code a domain code maps to.

func GetHTTPStatus

func GetHTTPStatus(code string) int

GetHTTPStatus returns the HTTP status for an error code, or 0 if not found

func GetNumericCode

func GetNumericCode(code string) string

GetNumericCode returns numeric code by error type

func GetUserMessage

func GetUserMessage(code, lang string) string

GetUserMessage returns user-friendly message for error code in specified language

func GetUserMessageWithDetails

func GetUserMessageWithDetails(code, lang, details string) string

GetUserMessageWithDetails returns user message with additional details

func HasCode

func HasCode(err error, code string) bool

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 Is

func Is(err error, code string) bool

Is checks if error matches the code

func IsDomainError

func IsDomainError(err error) bool

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

func IsInfraError(err error) bool

IsInfraError reports whether err came from the infrastructure layer — INFRA_*, REPO_*, or an EXT_* adapter code.

func IsRegistered

func IsRegistered(code string) bool

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

func IsRetryable(code string) bool

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

func Join(errs ...error) error

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

func LanguageFromContext(ctx context.Context) string

LanguageFromContext returns the language the context carries, falling back to the language set by SetProblemLanguage.

func LogError

func LogError(logger *zap.Logger, err error)

LogError logs error using zap logger with all available fields Usage in Handler layer ONLY:

errors.LogError(logger, err)

func LogInfo

func LogInfo(logger *zap.Logger, err error, message string)

LogInfo logs error information without full stack trace

func LogWarn

func LogWarn(logger *zap.Logger, err error)

LogWarn logs error as warning

func MapToHTTPStatus

func MapToHTTPStatus(code string) int

MapToHTTPStatus maps error code to HTTP status code

func MapToServiceError

func MapToServiceError(err error) error

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

func NegotiateLanguage(header string) string

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

func RecordErrorGlobal(ctx context.Context, err *AppError)

RecordErrorGlobal records an error in global metrics and executes hooks

func RecordGlobal

func RecordGlobal(ctx context.Context, err error)

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

func ResolverHook(resolver *Resolver) func(ctx context.Context, err *AppError)

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

func RetryImmediate(ctx context.Context, maxAttempts int, fn func() error) error

RetryImmediate executes a function with immediate retry (no delay)

func RetryLinear

func RetryLinear(ctx context.Context, maxAttempts int, delay time.Duration, fn func() error) error

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

func SafeExecute(ctx context.Context, fn func() error) (err error)

SafeExecute executes a function and recovers from panics

func SafeExecuteWithRetry

func SafeExecuteWithRetry(ctx context.Context, fn func() error) error

SafeExecuteWithRetry executes a function with panic recovery and retry logic

func SetHTTPStatus

func SetHTTPStatus(code string, status int)

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

func ShouldAlertOps(code string) bool

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

func WithLanguage(ctx context.Context, lang string) context.Context

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

func WithRetry(ctx context.Context, fn func() error) error

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

func WriteProblemCtx(ctx context.Context, w http.ResponseWriter, err error, instance string) error

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

func WriteProblemRequest(w http.ResponseWriter, r *http.Request, err error) error

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

func WriteResult(w http.ResponseWriter, status int, payload any, err error, instance string) error

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

func AutoSource(err *AppError) *AppError

AutoSource automatically adds caller info with proper skip level This should be called directly from repository/service functions

func AutoSourceSkip

func AutoSourceSkip(err *AppError, skip int) *AppError

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

func Flatten(err error) []*AppError

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

func MapDomainToServiceError(err error) *AppError

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

func MapInfraToServiceError(err error) *AppError

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

func MapRepoToServiceError(err error, notFoundCode ...string) *AppError

MapRepoToServiceError maps repository error to service error

func MapServiceToHandlerError

func MapServiceToHandlerError(err error) *AppError

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

func MapToApplicationError(err error) *AppError

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 New

func New(code, message string) *AppError

New creates new error. If message is empty, it is resolved from the registry.

func NewApplicationError

func NewApplicationError(code, message string) *AppError

NewApplicationError creates a new application-layer error. Pass "" as message to use the registered message for the code.

func NewBadRequest

func NewBadRequest(message string) *AppError

NewBadRequest creates a 400 Bad Request error

func NewConflict

func NewConflict(message string) *AppError

NewConflict creates a 409 Conflict error

func NewDomainError

func NewDomainError(code, message string) *AppError

NewDomainError creates a new domain error. Pass "" as message to use the registered message for the code.

func NewForbidden

func NewForbidden(message string) *AppError

NewForbidden creates a 403 Forbidden error

func NewHandlerError

func NewHandlerError(code, message string) *AppError

NewHandlerError creates a new handler error

func NewInfraError

func NewInfraError(code, message string) *AppError

NewInfraError creates a new infrastructure-layer error. Pass "" as message to use the registered message for the code.

func NewInternalError

func NewInternalError(message string) *AppError

NewInternalError creates a 500 Internal Server error

func NewNotFound

func NewNotFound(message string) *AppError

NewNotFound creates a 404 Not Found error

func NewRepoError

func NewRepoError(code, message string) *AppError

NewRepoError creates a new repository error

func NewServiceError

func NewServiceError(code, message string) *AppError

NewServiceError creates a new service error

func NewTimeoutError

func NewTimeoutError(message string) *AppError

NewTimeoutError creates a 504 Timeout error

func NewUnauthorized

func NewUnauthorized(message string) *AppError

NewUnauthorized creates a 401 Unauthorized error

func NewValidationError

func NewValidationError(message string) *AppError

NewValidationError creates a 400 Validation error

func RecoverFromPanic

func RecoverFromPanic(ctx context.Context) *AppError

RecoverFromPanic recovers from panic and converts it to an AppError

func Split

func Split(err error) (retryable, fatal []*AppError)

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

func WithCaller(err *AppError, skip int) *AppError

WithCaller automatically adds caller information to error Usage: errors.WithCaller(err, 0) - will get the caller of WithCaller

func WithSource

func WithSource(err *AppError, file, function string) *AppError

WithSource adds source file and function information to error This helps track where the error originated in the codebase

func Wrap

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

Wrap wraps an existing error. If message is empty, it is resolved from the registry.

func WrapApplicationError

func WrapApplicationError(err error, code, message string) *AppError

WrapApplicationError wraps an error as an application-layer error.

func WrapBadRequest

func WrapBadRequest(err error, message string) *AppError

WrapBadRequest wraps an error as 400 Bad Request

func WrapConflict

func WrapConflict(err error, message string) *AppError

WrapConflict wraps an error as 409 Conflict

func WrapDomainError

func WrapDomainError(err error, code, message string) *AppError

WrapDomainError wraps an error as a domain error.

func WrapForbidden

func WrapForbidden(err error, message string) *AppError

WrapForbidden wraps an error as 403 Forbidden

func WrapHandlerError

func WrapHandlerError(err error, code, message string) *AppError

WrapHandlerError wraps an error as handler error

func WrapInfraError

func WrapInfraError(err error, code, message string) *AppError

WrapInfraError wraps an error as an infrastructure-layer error.

func WrapInternal

func WrapInternal(err error, message string) *AppError

WrapInternal wraps an error as 500 Internal Server Error

func WrapNotFound

func WrapNotFound(err error, message string) *AppError

WrapNotFound wraps an error as 404 Not Found

func WrapRepoError

func WrapRepoError(err error, code, message string) *AppError

WrapRepoError wraps an error as repository error

func WrapServiceError

func WrapServiceError(err error, code, message string) *AppError

WrapServiceError wraps an error as service error

func WrapUnauthorized

func WrapUnauthorized(err error, message string) *AppError

WrapUnauthorized wraps an error as 401 Unauthorized

func (*AppError) Error

func (e *AppError) Error() string

Error interface implementation

func (*AppError) Fingerprint

func (e *AppError) Fingerprint() string

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

func (e *AppError) IsRetryable() bool

IsRetryable checks if this error is retryable

func (*AppError) MarshalJSON

func (e *AppError) MarshalJSON() ([]byte, error)

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

func (e *AppError) Problem(instance string) 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

func (e *AppError) ProblemCtx(ctx context.Context, instance string) Problem

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) String

func (e *AppError) String() string

String returns a formatted string representation

func (*AppError) Unwrap

func (e *AppError) Unwrap() error

Unwrap returns the wrapped error

func (*AppError) WithContext

func (e *AppError) WithContext(ctx context.Context) *AppError

WithContext enriches error with context information

func (*AppError) WithDetails

func (e *AppError) WithDetails(details string) *AppError

WithDetails adds detailed information

func (*AppError) WithExtension

func (e *AppError) WithExtension(key string, value any) *AppError

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) WithField

func (e *AppError) WithField(key string, value any) *AppError

WithField adds a field

func (*AppError) WithInput

func (e *AppError) WithInput(input any) *AppError

WithInput adds input data to error

func (*AppError) WithMetadata

func (e *AppError) WithMetadata(key string, value any) *AppError

WithMetadata adds metadata to error

func (*AppError) WithOperation

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

WithOperation adds operation name to error context

func (*AppError) WithOutput

func (e *AppError) WithOutput(output any) *AppError

WithOutput adds output data to error

func (*AppError) WithResource

func (e *AppError) WithResource(resource, resourceID string) *AppError

WithResource adds resource information to error

func (*AppError) WithRetryAfter

func (e *AppError) WithRetryAfter(d time.Duration) *AppError

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

func (e *AppError) WithSuggestion(suggestion string) *AppError

WithSuggestion adds a suggestion

func (*AppError) WithTag

func (e *AppError) WithTag(tag string) *AppError

WithTag adds a tag to error

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

type DomainError interface {
	error
	Code() string
}

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) Cleanup

func (c *ErrorChain) Cleanup()

Cleanup removes expired chains.

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

type ErrorHook func(ctx context.Context, err *AppError)

ErrorHook is a function that gets called when an error occurs

func AlertingHook

func AlertingHook(alertFn func(ctx context.Context, err *AppError)) ErrorHook

AlertingHook creates a hook that sends alerts for critical errors

func LoggingHook

func LoggingHook(logger *zap.Logger) ErrorHook

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
)

func GetLayer

func GetLayer(code string) ErrorLayer

GetLayer returns the layer for an error code

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

func (*ErrorMetrics) Reset

func (m *ErrorMetrics) Reset()

Reset resets all metrics

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) Error

func (m *MultiError) Error() string

Error summarizes the aggregate.

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

func (p Problem) MarshalJSON() ([]byte, error)

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

func (p *Problem) UnmarshalJSON(data []byte) error

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.

func (Problem) WithExtension

func (p Problem) WithExtension(key string, value any) Problem

WithExtension returns a copy of the problem carrying one more extension member. A reserved member name is ignored.

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 Reporter

type Reporter interface {
	SendError(err error) error
}

type ResolutionAction

type ResolutionAction func(ctx context.Context, err *AppError) bool

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 NewResolver

func NewResolver() *Resolver

NewResolver creates a new error resolver.

func (*Resolver) Register

func (r *Resolver) Register(code string, action ResolutionAction)

Register adds a resolution action for an error code.

func (*Resolver) Resolve

func (r *Resolver) Resolve(ctx context.Context, err *AppError) bool

Resolve attempts to automatically resolve an error. Returns true if a resolution was applied.

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

type RetryPolicy struct {
	Retryable  bool
	RetryAfter int // seconds
	MaxRetries int
}

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.

func (*Sampler) ShouldLog

func (s *Sampler) ShouldLog(code string) bool

ShouldLog returns true if this error should be logged.

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.

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.

Jump to

Keyboard shortcuts

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