apperr

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 5 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 package depends on 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.
  • 🪶 Zero dependencies — the go.mod requires only the standard library.
  • 🔧 Pluggable observability — tiny Recorder/Logger interfaces, no-op by default.
  • 📝 Docs-ready — render your whole code table as Markdown.

📦 Install

go get github.com/Bugs5382/go-apperr

No third-party dependencies come with it — you add a logger or tracer only if you wire one.

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

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.

🔌 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}))

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 is dependency-free: it 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, so a consumer's go.mod stays free of any dependency they did not choose.

Codes are the consumer's own namespace. The first-digit-of-code 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.

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.

Types

type Entry

type Entry struct {
	Code  int
	Title string
	Cause 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.

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.

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 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(digit int) Option

WithService validates that every registered code's first digit equals digit. It expresses the "each service owns a code prefix" convention: an app claims a leading digit so any code it emits is attributable to it at a glance.

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, and -- when WithService is set -- on any code whose first digit does not match the claimed service digit.

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.

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 |

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.

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 sanitized client message and the resolved code. 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
apperrgrpc module
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