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.