apperr

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 7 Imported by: 11

README

go-apperr 🔢

🏷️ Turn internal errors into stable, reportable numeric codes — with logging and tracing you plug in, not baked in.

An internal error should not leak its guts to a client, and "internal error" with no handle is useless in a bug report. go-apperr wraps a cause with a stable code that travels the error chain, and at the edge renders a sanitized, quotable message. 🔌 Bring your own logging and tracing: the core apperr package imports nothing beyond the standard library.

✨ Highlights

  • 🧬 Codes ride the error chain — errors.Is/errors.As keep working; recover the code anywhere.
  • 🧼 Sanitized at the edge — clients get a code they can quote, never the raw internal detail.
  • 🪶 Stdlib-only core — the apperr package imports only the standard library; a binary that imports just it links no gRPC code.
  • 🔧 Pluggable observability — tiny Recorder/Logger interfaces, no-op by default.
  • 📝 Docs-ready — render your whole code table as Markdown.
  • 🔤 Symbols and user-safe messages — a stable SCREAMING_SNAKE name per code, and an opt-in message end users may see.
  • 📨 Wire metadata — key/value pairs on one error that travel to the client.
  • 🛰️ gRPC adapter — the apperrgrpc subpackage builds a status with ErrorInfo and reads it back.

📦 Install

go get github.com/Bugs5382/go-apperr

One module, one version. The module requires gRPC (google.golang.org/grpc, google.golang.org/genproto/googleapis/rpc, google.golang.org/protobuf) for the apperrgrpc subpackage, so go get records those in your go.sum. Importing only the root apperr package still puts no gRPC code into your binary: Go's linker drops packages you never import. You add a logger or tracer only if you wire one.

The gRPC adapter ships in the same module; import it as github.com/Bugs5382/go-apperr/apperrgrpc.

🚀 Core usage

Wrap a cause with a code; recover it anywhere with Code. errors.Is/errors.As still traverse to the original cause.

err := apperr.Coded(1001, fmt.Errorf("load widget: %w", errDatabaseDown))

code, ok := apperr.Code(err)      // 1001, true
errors.Is(err, errDatabaseDown)   // true

Register your codes once at startup, then present internal errors as client-safe messages:

reg, err := apperr.NewRegistry([]apperr.Entry{
    {Code: 1001, Title: "database", Cause: "database unavailable"},
    {Code: 1002, Title: "upstream", Cause: "upstream timeout"},
}, apperr.WithService(1)) // this service owns the "1" prefix

msg, code := reg.Present(apperr.Coded(1002, dbErr), 1001)
// msg = "Code 1002: Internal Error", code = 1002
// an uncoded error falls back to the default code you pass.

A service prefix can be longer than one digit. WithService(12) accepts codes that start with 12, and WithCodeDigits fixes the code width so each prefix owns one range:

reg, err := apperr.NewRegistry(entries,
    apperr.WithService(12),     // this service owns the "12" prefix
    apperr.WithCodeDigits(5),   // five-digit codes: 12000 through 12999
)
// 13001, 1201 and 120001 fail registration; so does a duplicate code.

A one-digit prefix keeps its original rule (any code whose first digit matches), so existing registries keep their codes.

WithMessageTemplate overrides the client message; Describe looks a code back up for operators; Markdown renders the whole registry as a Code | Area | Cause table (sorted by code) for your error-codes doc. Once any entry sets a Symbol or UserSafe, the table becomes Code | Symbol | Area | Cause | User-safe; a registry that uses neither renders exactly as before.

🔤 Symbols and user-safe messages

An entry can name its code with an optional Symbol, so clients and translation catalogs key on a stable name instead of a number. A symbol must match ^[A-Z][A-Z0-9_]*$ and be unique in the registry; NewRegistry rejects anything else.

UserSafe says the entry's Message may be shown to end users. Present then returns that message instead of the generic template, filling each {key} placeholder from the error's wire metadata (see below):

reg, _ := apperr.NewRegistry([]apperr.Entry{
    {Code: 6001, Title: "resolver", Cause: "approver lookup failed"},
    {
        Code: 6010, Title: "swap", Cause: "candidate not eligible",
        Symbol: "SWAP_NOT_ELIGIBLE", Category: apperr.CategoryFailedPrecondition,
        UserSafe: true, Message: "That person isn't an eligible approver for stage {stage}.",
    },
})

msg, _ := reg.Present(apperr.WithMeta(apperr.Coded(6010, nil), apperr.Meta("stage", "2")), 6000)
// msg = "That person isn't an eligible approver for stage 2."

msg, _ = reg.Present(apperr.Coded(6001, dbErr), 6000)
// msg = "Code 6001: Internal Error"

🛡️ Safe by default: UserSafe is false unless an entry sets it, so every existing entry (and any unregistered code) still gets only the template and its code. A user-safe entry must have a non-blank Message. A Message on an entry that is not user-safe is never presented, but stays available through Describe for your docs or UI catalog. A placeholder with no matching key is left as written, and a substituted value is never scanned again. Message(code) always renders the template; Present and PresentContext are the paths that honour UserSafe.

📨 Wire metadata

WithMeta attaches key/value pairs to one error, and Metadata reads them back from anywhere in the chain (errors.Join trees included; an outer layer wins on a repeated key):

err := apperr.WithMeta(
    apperr.Coded(6010, fmt.Errorf("swap: %w", errNotEligible)),
    apperr.Meta("new_user_id", candidateID),
)

apperr.Metadata(err) // map[new_user_id:...]

The wrapped error keeps its Error() text, its code and its errors.Is/errors.As behaviour.

📌 Metadata is not Fields. They answer different questions:

Wire metadata (WithMeta) Request fields (ContextWithFields)
Describes this one failure the request
Lives on the error the context
Reaches the client (status details, message placeholders) the Recorder and Logger only

Never put anything in metadata the client may not see; log-only detail belongs in Fields or the wrapped cause.

🧭 Map to a transport

An entry can carry an optional, transport-neutral Category: CategoryInternal (the default when unset), CategoryNotFound, CategoryInvalid, CategoryUnavailable, CategoryPermissionDenied, CategoryFailedPrecondition, CategoryDeadlineExceeded, CategoryUnauthenticated or CategoryAlreadyExists. New categories are only ever appended, so no constant changes value. reg.Category(err) looks it up from a coded error, and falls back to internal for an uncoded or unregistered one. One small mapper per transport then covers every code:

reg, _ := apperr.NewRegistry([]apperr.Entry{
    {Code: 1002, Title: "widget", Cause: "widget not found", Category: apperr.CategoryNotFound},
})

// gRPC, in your server package
func grpcCode(c apperr.Category) codes.Code {
    switch c {
    case apperr.CategoryNotFound:
        return codes.NotFound
    case apperr.CategoryInvalid:
        return codes.InvalidArgument
    case apperr.CategoryUnavailable:
        return codes.Unavailable
    case apperr.CategoryPermissionDenied:
        return codes.PermissionDenied
    default:
        return codes.Internal
    }
}

msg, _ := reg.Present(err, 1000)
return status.Error(grpcCode(reg.Category(err)), msg)

// HTTP: the same switch returning http.StatusNotFound, http.StatusBadRequest,
// http.StatusServiceUnavailable, http.StatusForbidden or http.StatusInternalServerError
http.Error(w, msg, httpStatus(reg.Category(err)))

go-apperr itself imports neither transport; the mappers live in your code. The Markdown table is unchanged by categories, so existing error-codes docs stay in sync.

gRPC adapter

For gRPC you can skip the hand-written switch: apperrgrpc maps every category (Code) and builds the whole status. The status carries one errdetails.ErrorInfo whose Reason is the entry's Symbol (or the code when it has none), whose Domain is the one you pass, and whose Metadata is the error's wire metadata plus the numeric code under codeNum:

import "github.com/Bugs5382/go-apperr/apperrgrpc"

// server: present through the registry (sinks included) and return the status error
return nil, apperrgrpc.Error(ctx, reg, err, 6000, "workflow.example.org")

// client: read it back
if info, ok := apperrgrpc.FromError(err); ok {
    // info.Code == 6010, info.Symbol == "SWAP_NOT_ELIGIBLE",
    // info.Domain == "workflow.example.org", info.Metadata["new_user_id"] == candidateID
}

codeNum always rides along, so a relaying service recovers the original code without a copy of the remote registry. FromStatus does the same for a *status.Status. The adapter is a subpackage of the root module (github.com/Bugs5382/go-apperr/apperrgrpc); a service that imports only apperr links none of its gRPC code.

🔌 Bring your own logging and tracing

The package calls two tiny interfaces, defaulting to no-ops:

type Recorder interface { RecordCode(ctx context.Context, code int, err error) }
type Logger   interface { LogCoded(ctx context.Context, code int, err error) }

Wire them with WithRecorder/WithLogger; PresentContext drives them while returning the same sanitized message and code. On any stack, an adapter is a few lines — here a log/slog logger:

type slogLogger struct{ log *slog.Logger }

func (s slogLogger) LogCoded(ctx context.Context, code int, err error) {
    s.log.ErrorContext(ctx, "coded error", "code", code, "error", err)
}

reg, _ := apperr.NewRegistry(entries, apperr.WithLogger(slogLogger{log: mySlog}))

To get request metadata (method, route, and so on) into the sinks, attach it to the context once at the edge. A sink reads it back from the ctx it already receives, so the interfaces stay the same:

ctx = apperr.ContextWithFields(ctx,
    apperr.Field{Key: "method", Value: r.Method},
    apperr.Field{Key: "route", Value: route},
)
msg, code := reg.PresentContext(ctx, err, 1001)

// inside a sink
for _, f := range apperr.FieldsFromContext(ctx) {
    args = append(args, f.Key, f.Value)
}

Fields keep the order they were added, and FieldsFromContext returns nil when there are none.

A Recorder plugs in the same way — implement RecordCode over your tracer (OpenTelemetry, etc.) to set the code on the active span. Nothing is bundled, so your go.mod stays free of any dependency you did not choose. 🎯

📚 Examples

Runnable programs under examples/: coded, registry, markdown, and custom (bring-your-own sinks over log/slog).

📐 Where this belongs

Use go-apperr in application code — the service that owns its code namespace and presents errors at the edge. Don't depend on it from another reusable library: libraries should return plain wrapped errors and let the app assign codes. Each app owns its own prefix (WithService) so a code is attributable at a glance.

🛠 Develop

task build    # go build ./...
task test     # go test ./...
task lint     # gofmt + golangci-lint + yamllint
task license  # inject MIT headers (golic)

⚖️ License

MIT © 2026 Shane

Documentation

Overview

Package apperr turns internal errors into stable, reportable numeric codes.

A service wraps an internal cause with Coded(code, cause). The code travels with the error through the normal error chain, so errors.Is and errors.As keep working, and Code(err) recovers the nearest code at any boundary. At the edge, a Registry the consumer builds at startup maps each code to a sanitized, client-safe message: the caller learns a code they can quote in a bug report, never the raw internal detail.

The package imports no logging, tracing, or third-party package, only the standard library. Observability is pluggable through two small interfaces, Recorder and Logger, wired with WithRecorder and WithLogger and defaulting to no-ops. Bring any stack -- log/slog, OpenTelemetry, zap -- by writing a few-line adapter that implements them (see the examples). Nothing is bundled into this package. The module does require gRPC for the apperrgrpc subpackage, but a binary that imports only this package links no gRPC code: Go's linker drops packages that are never imported.

Codes are the consumer's own namespace. The service prefix convention (WithService) is one supported way to let each service own a code prefix so a code is easy to attribute at a glance; it is optional. A prefix may be one digit or several, and WithCodeDigits fixes the code width so each prefix owns a single range (WithService(12) with WithCodeDigits(5) owns 12000-12999).

An Entry may also declare a transport-neutral Category (internal by default). Registry.Category looks it up from a coded error, so one mapper per transport can turn any code into a gRPC or HTTP status without this package importing either.

An Entry may also name its code with a Symbol (SCREAMING_SNAKE_CASE, unique in the registry) and opt in to UserSafe, which makes Present return the entry's own Message, with {key} placeholders filled from the error's wire metadata, instead of the generic template. UserSafe is false by default, so an entry that does not opt in is presented exactly as before. Markdown adds Symbol and User-safe columns once any entry uses them.

WithMeta attaches wire metadata to one error and Metadata reads it back. Unlike request Fields, which describe the request and reach only the sinks, wire metadata describes the failure and is meant to reach the client. The apperrgrpc subpackage sends the symbol, metadata and numeric code as a gRPC ErrorInfo and parses them back.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Code

func Code(err error) (code int, ok bool)

Code returns the code carried by err, walking the error chain with errors.As and returning the nearest coded error's code. It reports (0, false) when err is nil or carries no code, so a caller can distinguish "no code" from a legitimately zero code.

Example

ExampleCode recovers the stable code from a wrapped internal error.

package main

import (
	"errors"
	"fmt"

	apperr "github.com/Bugs5382/go-apperr"
)

func main() {
	err := apperr.Coded(1001, errors.New("database unavailable"))
	code, ok := apperr.Code(err)
	fmt.Println(code, ok)
}
Output:
1001 true

func Coded

func Coded(code int, cause error) error

Coded wraps cause with a stable numeric code. The returned error's Unwrap returns cause, so errors.Is and errors.As traverse to it unchanged; the code rides alongside and is recovered with Code. A nil cause is allowed -- the result is a bare coded marker whose Error reports only the code.

func ContextWithFields added in v1.1.0

func ContextWithFields(ctx context.Context, fields ...Field) context.Context

ContextWithFields returns a child of ctx carrying fields after any fields ctx already has. Order is kept and duplicate keys are not merged: a sink sees every field in the order it was added and decides how to render repeats. The parent context is never modified, so sibling requests do not share fields. With no fields it returns ctx unchanged.

Example

ExampleContextWithFields attaches request metadata at the edge and reads it back the way a sink would, from the ctx it already receives.

package main

import (
	"context"
	"fmt"

	apperr "github.com/Bugs5382/go-apperr"
)

func main() {
	ctx := apperr.ContextWithFields(context.Background(),
		apperr.Field{Key: "method", Value: "GET"},
		apperr.Field{Key: "route", Value: "/widgets/{id}"},
	)
	for _, f := range apperr.FieldsFromContext(ctx) {
		fmt.Printf("%s=%v\n", f.Key, f.Value)
	}
}
Output:
method=GET
route=/widgets/{id}

func Metadata added in v1.2.0

func Metadata(err error) map[string]string

Metadata returns the wire metadata attached to err with WithMeta anywhere in its chain, including inside errors.Join trees. When two layers set the same key, the outer one (the one seen first, walking the chain as errors.As does) wins. It returns nil when err is nil or carries no metadata. The result is a copy.

func WithMeta added in v1.2.0

func WithMeta(err error, pairs ...MetaPair) error

WithMeta returns err carrying the given wire metadata: key/value pairs that describe this one failure and travel with it to the client, such as the ID a request was refused for. A transport adapter (see the apperrgrpc package) puts them on the wire, and a user-safe Entry's Message fills its {key} placeholders from them. Recover them with Metadata.

Wire metadata is not the same as request Fields. Fields (ContextWithFields) describe the request, live on the context, and reach only the Recorder and Logger; they are never sent to the client. Metadata describes the error, lives on the error, and is meant to be sent. Put nothing in it the client may not see.

The result's Error, Code, errors.Is and errors.As behave exactly as for err. A later pair overrides an earlier one with the same key. WithMeta returns nil for a nil err, and err itself when there are no pairs.

Example

ExampleWithMeta attaches wire metadata to one coded error: the refused candidate's ID travels with the error to the client.

package main

import (
	"errors"
	"fmt"

	apperr "github.com/Bugs5382/go-apperr"
)

func main() {
	err := apperr.WithMeta(
		apperr.Coded(6010, errors.New("candidate not in the eligible pool")),
		apperr.Meta("new_user_id", "u-2"),
	)
	code, _ := apperr.Code(err)
	fmt.Println(code, apperr.Metadata(err)["new_user_id"])
	fmt.Println(err)
}
Output:
6010 u-2
code 6010: candidate not in the eligible pool

Types

type Category added in v1.1.0

type Category int

Category is a transport-neutral class of failure for a registered code. It lets one shared mapper per transport (a gRPC status, an HTTP status) turn any coded error into the right response, instead of every service keeping its own code-to-status table. The package never imports a transport; see the Registry.Category examples for gRPC and HTTP mappers, and the apperrgrpc module for a ready-made gRPC one. New categories are only ever appended, so a constant's value never changes.

The zero value is CategoryInternal, so an Entry that sets no Category is internal, exactly as before categories existed.

Example

ExampleCategory lists the categories added after the first five; existing constants keep their values.

package main

import (
	"fmt"

	apperr "github.com/Bugs5382/go-apperr"
)

func main() {
	for _, c := range []apperr.Category{
		apperr.CategoryFailedPrecondition,
		apperr.CategoryDeadlineExceeded,
		apperr.CategoryUnauthenticated,
		apperr.CategoryAlreadyExists,
	} {
		fmt.Println(int(c), c)
	}
}
Output:
5 failed-precondition
6 deadline-exceeded
7 unauthenticated
8 already-exists
const (
	// CategoryInternal is an unexpected server-side failure. It is the default.
	CategoryInternal Category = iota
	// CategoryNotFound means the requested resource does not exist.
	CategoryNotFound
	// CategoryInvalid means the caller sent a malformed or invalid request.
	CategoryInvalid
	// CategoryUnavailable means a dependency is down or overloaded and the
	// caller may retry later.
	CategoryUnavailable
	// CategoryPermissionDenied means the caller is known but not allowed to do
	// this.
	CategoryPermissionDenied
	// CategoryFailedPrecondition means the request is valid but the system is
	// not in a state that allows it, such as a stage with no approver yet.
	// Retrying will not help until that state changes.
	CategoryFailedPrecondition
	// CategoryDeadlineExceeded means the operation ran out of time before it
	// finished.
	CategoryDeadlineExceeded
	// CategoryUnauthenticated means the caller has no valid credentials.
	CategoryUnauthenticated
	// CategoryAlreadyExists means the thing the caller tried to create exists
	// already.
	CategoryAlreadyExists
)

func (Category) String added in v1.1.0

func (c Category) String() string

String returns the category's stable name ("internal", "not-found", "invalid", "unavailable", "permission-denied", "failed-precondition", "deadline-exceeded", "unauthenticated", "already-exists"), suitable for a log field or span attribute. An unknown value renders as "Category(n)".

type Entry

type Entry struct {
	Code     int
	Title    string
	Cause    string
	Category Category
	Symbol   string
	UserSafe bool
	Message  string
}

Entry describes one code the consumer registers. Title is a short area/label for the code; Cause is a one-line internal description. Both are for the consumer's own error-codes documentation (see Markdown) and are never shown to a client -- only the code and the rendered message template are.

Category is optional and transport-neutral; left unset it is CategoryInternal. Registry.Category reads it back from a coded error.

Symbol is an optional stable name for the code in SCREAMING_SNAKE_CASE (matching ^[A-Z][A-Z0-9_]*$), unique within the registry. Clients and translation catalogs can key on it instead of the number; the apperrgrpc module sends it as the ErrorInfo reason.

UserSafe says Message may be shown to end users. Present returns Message for a user-safe entry, with each {key} placeholder filled from the error's wire metadata (see WithMeta), and the generic message template for every other entry. The zero value is false, so an entry that does not opt in is presented exactly as before UserSafe existed: only the code, never a message. A user-safe entry must have a non-blank Message. A Message on an entry that is not user-safe is never presented; it can still feed the consumer's own docs or UI catalog through Describe.

Example (UserSafe)

ExampleEntry_userSafe shows the end user a user-safe entry's message, filled from the error's metadata, while an entry that does not opt in keeps the generic template.

package main

import (
	"errors"
	"fmt"

	apperr "github.com/Bugs5382/go-apperr"
)

func main() {
	reg, err := apperr.NewRegistry([]apperr.Entry{
		{Code: 6001, Title: "resolver", Cause: "approver lookup failed"},
		{
			Code: 6010, Title: "swap", Cause: "candidate not eligible",
			Symbol: "SWAP_NOT_ELIGIBLE", Category: apperr.CategoryFailedPrecondition,
			UserSafe: true, Message: "That person isn't an eligible approver for stage {stage}.",
		},
	})
	if err != nil {
		panic(err)
	}

	refused := apperr.WithMeta(apperr.Coded(6010, nil), apperr.Meta("stage", "2"))
	msg, _ := reg.Present(refused, 6000)
	fmt.Println(msg)

	msg, _ = reg.Present(apperr.Coded(6001, errors.New("dial tcp: refused")), 6000)
	fmt.Println(msg)
}
Output:
That person isn't an eligible approver for stage 2.
Code 6001: Internal Error

type Field added in v1.1.0

type Field struct {
	Key   string
	Value any
}

Field is one request-scoped key/value pair for the sinks, such as the request method or route. Attach fields to a context with ContextWithFields at the edge of a request; a Recorder or Logger reads them back with FieldsFromContext from the ctx it already receives, so the sink signatures do not change.

func FieldsFromContext added in v1.1.0

func FieldsFromContext(ctx context.Context) []Field

FieldsFromContext returns the request fields attached to ctx, in the order they were added. It returns nil when ctx carries none (or is nil). The result is a copy, so a sink may modify it freely.

type Logger

type Logger interface {
	LogCoded(ctx context.Context, code int, err error)
}

Logger is the neutral logging sink the observability-aware present path calls. An implementation emits one structured line carrying the code and, when the backend correlates traces, the trace_id. As with Recorder, this package ships only a no-op; a small custom shim over the consumer's logger (log/slog, zap, etc.) provides the real thing.

Both sinks can read request-scoped fields (method, route, and so on) the caller attached with ContextWithFields by calling FieldsFromContext on ctx.

type MetaPair added in v1.2.0

type MetaPair struct {
	Key   string
	Value string
}

MetaPair is one key/value pair of wire metadata, built with Meta.

func Meta added in v1.2.0

func Meta(key, value string) MetaPair

Meta returns one key/value pair of wire metadata for WithMeta.

type Option

type Option func(*Registry)

Option configures a Registry at construction. All options are optional; the zero configuration is a plain code table with the default message template and no-op observability.

func WithCodeDigits added in v1.1.0

func WithCodeDigits(n int) Option

WithCodeDigits requires every registered code to have exactly n decimal digits (sign ignored). With WithService it fixes each service's code range from the prefix length: a prefix of length L owns the n-L trailing digits, so WithService(12) with WithCodeDigits(5) accepts 12000 through 12999 and rejects anything outside it. NewRegistry fails when n is not positive or leaves no digit after the prefix.

Example

ExampleWithCodeDigits gives a service a two-digit prefix and fixed-width codes, so it owns 12000 through 12999 and anything else fails registration.

package main

import (
	"fmt"

	apperr "github.com/Bugs5382/go-apperr"
)

func main() {
	_, err := apperr.NewRegistry([]apperr.Entry{
		{Code: 12001, Title: "database", Cause: "database unavailable"},
	}, apperr.WithService(12), apperr.WithCodeDigits(5))
	fmt.Println(err)

	_, err = apperr.NewRegistry([]apperr.Entry{
		{Code: 13001, Title: "database", Cause: "database unavailable"},
	}, apperr.WithService(12), apperr.WithCodeDigits(5))
	fmt.Println(err)
}
Output:
<nil>
apperr: code 13001 does not start with service prefix 12

func WithLogger

func WithLogger(l Logger) Option

WithLogger installs a logging sink invoked by PresentContext. A nil Logger is ignored, leaving the no-op default in place.

func WithMessageTemplate

func WithMessageTemplate(tmpl string) Option

WithMessageTemplate overrides the sanitized client message. tmpl is a fmt-style template that receives the code (include a %d), e.g. "Something went wrong (ref %d)". The default is "Code %d: Internal Error".

func WithRecorder

func WithRecorder(rec Recorder) Option

WithRecorder installs a tracing sink invoked by PresentContext. A nil Recorder is ignored, leaving the no-op default in place.

func WithService

func WithService(prefix int) Option

WithService validates that every registered code starts with the decimal digits of prefix. It expresses the "each service owns a code prefix" convention: an app claims a prefix so any code it emits is attributable to it at a glance.

A one-digit prefix behaves as it always has: WithService(1) accepts any code whose first digit is 1 (1, 12, 1001, ...). A longer prefix works the same way on more digits, so WithService(12) accepts 12001 and rejects 1001 and 13001. The sign of a code is ignored. Pair it with WithCodeDigits to pin every code to one fixed-width range derived from the prefix length.

type Recorder

type Recorder interface {
	RecordCode(ctx context.Context, code int, err error)
}

Recorder is the neutral tracing sink the observability-aware present path calls. An implementation records the resolved code (and, if it wants, the error) on the active span or whatever backend it wraps. This package ships only a no-op; a real Recorder is a few lines of the consumer's own code over their tracer of choice (OpenTelemetry, etc.) -- see the examples.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry is the consumer's own set of codes plus the presentation and observability policy around them. Build one at startup with NewRegistry and share it; it is read-only afterward and safe for concurrent use.

func NewRegistry

func NewRegistry(entries []Entry, opts ...Option) (*Registry, error)

NewRegistry builds a Registry from the consumer's codes and options. It fails on a duplicate code, on any code outside the service prefix when WithService is set, on any code of the wrong width when WithCodeDigits is set, on an unknown Category value, on a malformed or duplicate Symbol, and on a user-safe entry with a blank Message.

func (*Registry) Category added in v1.1.0

func (r *Registry) Category(err error) Category

Category returns the category registered for the code carried by err. It walks the error chain the same way Code does. An uncoded error, a nil error, or a code that is not registered is CategoryInternal, so a mapper always has a safe answer.

Example (Grpc)

ExampleRegistry_Category_grpc shows one shared gRPC mapper: the handler looks up the category from the coded error and turns it into a status code, with the sanitized message from Present as the status message.

package main

import (
	"errors"
	"fmt"

	apperr "github.com/Bugs5382/go-apperr"
)

// grpcCode maps a category to a gRPC status code number. The numbers are the
// stable values from the gRPC spec (NotFound is 5, and so on), written out so
// this package never imports a transport. A real mapper would return
// codes.Code from google.golang.org/grpc/codes instead of an int.
func grpcCode(c apperr.Category) int {
	switch c {
	case apperr.CategoryNotFound:
		return 5
	case apperr.CategoryInvalid:
		return 3
	case apperr.CategoryUnavailable:
		return 14
	case apperr.CategoryPermissionDenied:
		return 7
	default:
		return 13
	}
}

func main() {
	reg, err := apperr.NewRegistry([]apperr.Entry{
		{Code: 1002, Title: "widget", Cause: "widget not found", Category: apperr.CategoryNotFound},
	})
	if err != nil {
		panic(err)
	}
	internal := apperr.Coded(1002, errors.New("select widget: no rows"))
	msg, _ := reg.Present(internal, 1000)
	// In a real server: status.Error(codes.Code(grpcCode(...)), msg)
	fmt.Printf("grpc code %d: %s\n", grpcCode(reg.Category(internal)), msg)
}
Output:
grpc code 5: Code 1002: Internal Error
Example (Http)

ExampleRegistry_Category_http shows the same idea for HTTP: one mapper from category to status, shared by every handler.

package main

import (
	"errors"
	"fmt"

	apperr "github.com/Bugs5382/go-apperr"
)

// httpStatus maps a category to an HTTP status. A real mapper would use the
// net/http constants (http.StatusNotFound, and so on).
func httpStatus(c apperr.Category) int {
	switch c {
	case apperr.CategoryNotFound:
		return 404
	case apperr.CategoryInvalid:
		return 400
	case apperr.CategoryUnavailable:
		return 503
	case apperr.CategoryPermissionDenied:
		return 403
	default:
		return 500
	}
}

func main() {
	reg, err := apperr.NewRegistry([]apperr.Entry{
		{Code: 1005, Title: "auth", Cause: "caller lacks role", Category: apperr.CategoryPermissionDenied},
	})
	if err != nil {
		panic(err)
	}
	internal := apperr.Coded(1005, errors.New("role check failed"))
	msg, _ := reg.Present(internal, 1000)
	// In a real handler: http.Error(w, msg, httpStatus(...))
	fmt.Printf("http %d: %s\n", httpStatus(reg.Category(internal)), msg)
}
Output:
http 403: Code 1005: Internal Error

func (*Registry) Describe

func (r *Registry) Describe(code int) (Entry, bool)

Describe returns the registered Entry for code and whether it was found.

func (*Registry) Markdown

func (r *Registry) Markdown() string

Markdown renders the registry as a "Code | Area | Cause" table, sorted by code so the output is deterministic. It is meant to be written into a consumer's error-codes reference document.

When any entry sets a Symbol or is UserSafe, the table becomes "Code | Symbol | Area | Cause | User-safe", so a registry that does not use them renders exactly as before.

Example

ExampleRegistry_Markdown renders the registry as a docs table, sorted by code.

package main

import (
	"fmt"

	apperr "github.com/Bugs5382/go-apperr"
)

func main() {
	reg, err := apperr.NewRegistry([]apperr.Entry{
		{Code: 1002, Title: "upstream", Cause: "upstream timeout"},
		{Code: 1001, Title: "database", Cause: "database unavailable"},
	})
	if err != nil {
		panic(err)
	}
	fmt.Print(reg.Markdown())
}
Output:
| Code | Area | Cause |
| --- | --- | --- |
| 1001 | database | database unavailable |
| 1002 | upstream | upstream timeout |
Example (Symbols)

ExampleRegistry_Markdown_symbols adds the Symbol and User-safe columns once an entry uses them.

package main

import (
	"fmt"

	apperr "github.com/Bugs5382/go-apperr"
)

func main() {
	reg, err := apperr.NewRegistry([]apperr.Entry{
		{Code: 1001, Title: "database", Cause: "database unavailable"},
		{Code: 1002, Title: "widget", Cause: "widget not found", Symbol: "WIDGET_NOT_FOUND", UserSafe: true, Message: "That widget no longer exists."},
	})
	if err != nil {
		panic(err)
	}
	fmt.Print(reg.Markdown())
}
Output:
| Code | Symbol | Area | Cause | User-safe |
| --- | --- | --- | --- | --- |
| 1001 |  | database | database unavailable | no |
| 1002 | `WIDGET_NOT_FOUND` | widget | widget not found | yes |

func (*Registry) Message

func (r *Registry) Message(code int) string

Message renders the sanitized client message for code via the template. It works for any code, registered or not, so an unexpected code still yields a safe, quotable message rather than leaking internals. It always uses the template, even for a user-safe entry; Present is the path that returns a user-safe entry's own Message.

func (*Registry) Present

func (r *Registry) Present(err error, defaultCode int) (clientMsg string, code int)

Present resolves the code from err (the nearest coded error) or falls back to defaultCode when err carries none, and returns the client message and the resolved code. The message is the entry's own Message when the resolved code is registered as UserSafe, with {key} placeholders filled from Metadata(err); otherwise it is the sanitized template. It has no side effects; use PresentContext to also drive the Recorder and Logger.

Example

ExampleRegistry_Present turns an internal error into a sanitized, quotable client message and its code.

package main

import (
	"errors"
	"fmt"

	apperr "github.com/Bugs5382/go-apperr"
)

func main() {
	reg, err := apperr.NewRegistry([]apperr.Entry{
		{Code: 1002, Title: "upstream", Cause: "upstream timeout"},
	})
	if err != nil {
		panic(err)
	}
	msg, code := reg.Present(apperr.Coded(1002, errors.New("i/o timeout")), 1000)
	fmt.Printf("%s | %d\n", msg, code)
}
Output:
Code 1002: Internal Error | 1002

func (*Registry) PresentContext

func (r *Registry) PresentContext(ctx context.Context, err error, defaultCode int) (clientMsg string, code int)

PresentContext is Present plus observability: after resolving the code it calls the configured Recorder and Logger with ctx, the code, and err. With the default no-op sinks it behaves exactly like Present.

Directories

Path Synopsis
Package apperrgrpc carries go-apperr coded errors across gRPC.
Package apperrgrpc carries go-apperr coded errors across gRPC.
examples
coded command
Command coded shows the core primitives: wrap an internal cause with a stable code, then recover the code at a boundary while errors.Is still traverses to the original cause.
Command coded shows the core primitives: wrap an internal cause with a stable code, then recover the code at a boundary while errors.Is still traverses to the original cause.
custom command
Command custom shows "bring your own" observability.
Command custom shows "bring your own" observability.
markdown command
Command markdown renders a registry as a Markdown table, the kind you commit as an error-codes reference.
Command markdown renders a registry as a Markdown table, the kind you commit as an error-codes reference.
registry command
Command registry shows a consumer registering its own codes and turning internal errors into sanitized, quotable client messages.
Command registry shows a consumer registering its own codes and turning internal errors into sanitized, quotable client messages.

Jump to

Keyboard shortcuts

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