apperr

package
v0.21.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package apperr gives errors their meaning: a code a caller can handle, which side is responsible (scope), a default message for quick display, typed details for programmatic handling, and the steps the error passed through.

A formal error is made with New or Encapsulate, or by returning a code itself. Steps are added by apptracing when a step ends. Everything else — a plain error, a fmt.Errorf wrap, another module's error, a join — is unclassified, and is rendered as internal_server_error.

Codes are public or internal. Public codes are the contract with clients: this package defines the few generic to any host, and a host defines the rest with DefinePublicCode. Any package may define internal codes for its own callers to handle; each maps to a defined code, which is what a client sees.

Every code belongs to a namespace, one per module, so modules name their codes independently: a name is unique within its namespace. A client sees the bare name (not_found), the log the qualified one (apperr.not_found).

A library's codes are its own contract, not its host's. A host serves only its own codes and the generic ones: where it calls the library, it translates the library's errors to its own codes (Translate), which re-decides their scope, and refuses to serve any it did not.

A code knows nothing of any transport: an HTTP status is for the HTTP transport to assign, per public code.

Index

Constants

This section is empty.

Variables

View Source
var (
	InternalServerError = DefinePublicCode(Generic, "internal_server_error", Server, "Something went wrong on our side.")
	InvalidRequest      = DefinePublicCodeWith[Violations](Generic, "invalid_request", Client, "The request is not valid.")
	NotFound            = DefinePublicCode(Generic, "not_found", User, "Not found.")
	// ValidationFailed: the request was well-formed, and its input's meaning is
	// refused — a value out of range, a name already taken, an arg that does not
	// apply. Its violations name each field.
	ValidationFailed = DefinePublicCodeWith[Violations](Generic, "validation_failed", User, "Some of the input is not valid.")
)

The codes generic to any host. A host defines the rest of its contract with DefinePublicCode.

View Source
var Generic = DefineNamespace("apperr")

Generic is the namespace of the codes generic to any host, whose names no other namespace may define.

Functions

func DetailsOf

func DetailsOf[D any](err error, c TypedCode[D]) (details D, ok bool)

DetailsOf finds the formal error with code c in err's chain, or with an internal code mapped to c, and returns its details as c types them. ok reports whether the chain has c at all; the details are zero when the error carries none.

It reads err's own details at c, which a translation does not change: the library's error beneath a host's Translate keeps the library's.

func DisableErrorEncapsulation

func DisableErrorEncapsulation()

DisableErrorEncapsulation makes every error show its cause to clients, for a local entry point whose user is its operator: the person looking at a failed chart is the one who can fix it, and the log is not where they look.

From then on:

  • Encapsulate discloses the inner error's steps, as Translate does, and with no message of its own shows the inner error's rather than its code's default.
  • An internal_server_error shows its own message, an unclassified one the text of the error it formalised, instead of the generic message.

Call it once, at the start of such an entry point, before any error is made. It cannot be undone, and a host serving other people must never call it: the default keeps causes hidden.

func Encapsulate

func Encapsulate(inner error, c AnyCode, msg string) error

Encapsulate makes a formal error from an existing one, which becomes its inner error: kept for the log and for errors.Is, hidden from clients along with the steps beneath it. Chain only what actually caused the failure.

An empty msg uses the code's default message.

func EncapsulateWith

func EncapsulateWith[D any](inner error, c TypedCode[D], msg string, details D) error

EncapsulateWith is Encapsulate with typed details.

func New

func New(c AnyCode, msg string) error

New makes a formal error that starts here. An empty msg uses the code's default message.

func NewWith

func NewWith[D any](c TypedCode[D], msg string, details D) error

NewWith is New with typed details.

func Translate

func Translate(err error, c AnyCode) error

Translate re-codes err, a failure under another module's code, as c: where a host calls a library, it is how the library's errors become the host's. It is the same failure, so err's message and context stay visible to clients — its code, details and chain do not, and the log keeps all of it. To show a different message, or hide the context, encapsulate instead.

Only an internal_server_error's message is never carried over: it is a diagnosis, so c's default message is used — unless encapsulation is disabled (DisableEncapsulation).

func TranslateWith

func TranslateWith[D any](err error, c TypedCode[D], details D) error

TranslateWith is Translate with typed details: c's own, since err's are its module's type. Read err's with DetailsOf.

func WithStep

func WithStep(err error, step appstep.Step) error

WithStep records that err passed through a step, leaving its meaning as it was. apptracing calls it when a step ends; application code starts a step instead.

A formal error — or a bare code — comes back as a copy with the step added in front of its steps; the original is not mutated. Anything else is formalised as an unclassified internal_server_error carrying the step: it would render as that anyway, and the flag keeps "nobody classified this" apart from "somebody decided internal_server_error".

Types

type AnyCode

type AnyCode interface {
	error
	Code() Code
}

AnyCode is a Code or a TypedCode.

type Code

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

Code identifies a kind of failure. It is comparable, and it is itself an error: returning a code returns a formal error with the code's default message, and errors.Is(err, code) reports whether err was caused by a failure with that code.

Codes are made only by the Define functions, so a code cannot be invented at a call site or paired with the wrong scope.

func Codes

func Codes(ns Namespace) []Code

Codes returns ns's public codes, sorted by name: its module's contract with clients. A host's contract is its own namespace's and Generic's.

func DefineInternalCode

func DefineInternalCode(ns Namespace, name string, public Code, message string) Code

DefineInternalCode defines a code of ns for callers inside its module to handle. A client sees public instead, with this code's message carried over, so the message must be safe for callers.

func DefinePublicCode

func DefinePublicCode(ns Namespace, name string, scope Scope, message string) Code

DefinePublicCode defines a public code of ns: one a client can handle, with the scope it states and a default message for quick display. Call it from a package-level var, once per name; a name already in ns or one of the generic codes' names, no scope, or no message panics at startup.

Mint a public code only when a client should act differently from how it acts on every existing one.

func (Code) As

func (c Code) As(target any) bool

As lets errors.As find a bare code as a formal error, with the code's default message.

func (Code) Code

func (c Code) Code() Code

Code returns c itself, so that a Code satisfies AnyCode. The method exists for TypedCode, whose Code is otherwise unreachable from outside this package.

func (Code) DetailsType

func (c Code) DetailsType() reflect.Type

DetailsType is the type of the details a client receives with c: its public code's, since an internal code's details are its public code's. Nil when the code carries none.

func (Code) Error

func (c Code) Error() string

Error is the log form of a bare code: its qualified name and default message.

func (Code) Is

func (c Code) Is(target error) bool

Is lets errors.Is match a code by the code itself or by the public code it maps to, so a check for validation_failed also matches an internal code that renders as one.

func (Code) IsPublic

func (c Code) IsPublic() bool

IsPublic reports whether the code is part of its module's contract with clients: a defined code, not an internal one.

func (Code) Message

func (c Code) Message() string

Message is the code's default message.

func (Code) Namespace

func (c Code) Namespace() Namespace

Namespace is the namespace the code was defined in.

func (Code) Public

func (c Code) Public() Code

Public is the public code a client sees: the code itself if it is public, the code it maps to if it is internal.

func (Code) Qualified

func (c Code) Qualified() string

Qualified is the code's name qualified by its namespace, as the log sees it: apperr.not_found.

func (Code) Scope

func (c Code) Scope() Scope

Scope is which side the code says is responsible — its public code's.

func (Code) String

func (c Code) String() string

String is the code's name, as a client sees it.

type ContextEntry

type ContextEntry struct {
	Step   string         `json:"step"`
	Params map[string]any `json:"params,omitempty"`
	Text   string         `json:"text"`
}

ContextEntry is the wire form of a public step's description (appstep.Step.Describe): its id, the parameters its template names, and the rendered text — a lowercase verb phrase, made to be chained with ": " before the message. It is apperr's contract with clients, so it is apperr's type: appstep describes a step, and Response decides how that appears.

type Envelope

type Envelope struct {
	Error Response `json:"error"`
}

Envelope is what every transport sends: {"error": {...}}, so a body is self-describing wherever it turns up.

type Error

type Error struct {
	Code    Code
	Message string
	Details any
	// Steps are the steps the error passed through since it was made,
	// outermost first. Added by WithStep, on a copy.
	Steps []appstep.Step
	// contains filtered or unexported fields
}

Error is a formal error: a failure with a code, and the steps it passed through since it was made. Reach it with errors.As, which finds the outermost formal error in a chain.

Its inner error, if any, stays reachable to errors.Is and errors.As and to the log. It is hidden from clients, along with the inner error's own steps, unless the error discloses them: Translate does, and so does Encapsulate once DisableErrorEncapsulation was called.

func From

func From(err error) *Error

From returns the formal error a response is built from. Nil for nil.

Only the outermost value counts: a formal error, or a bare code with its default message. Anything else — a plain error, a fmt.Errorf wrap, a third-party wrapper, a join — is unclassified, so internal. That is stricter than errors.As, which looks through a foreign wrapper; code that wraps with fmt.Errorf is flagged by the linter. A step never leaves a foreign wrapper outermost: it formalises whatever passes through it.

Log err itself: its text is the whole chain.

func (*Error) Error

func (e *Error) Error() string

Error is the log form: the steps, outermost first, then the qualified code and message, then the inner chain. Sensitive step parameters are redacted. A message the inner chain already says, as when it was taken from the inner error, is not repeated.

func (*Error) Is

func (e *Error) Is(target error) bool

Is lets errors.Is match the error's code, or the public code it maps to.

func (*Error) Response

func (e *Error) Response(requestID string) Response

Response renders e for a client, with no Status: that is the transport's to set. An internal code renders as its public code, with its message and details carried over. Its context describes e's public steps, then those e discloses of its inner error (Translate). The internal server error renders only its default message: any other message for it is a diagnosis, and goes to the log — unless DisableErrorEncapsulation was called.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the inner error.

type Namespace

type Namespace = appstep.Namespace

Namespace is a module's namespace, shared with its steps: a code's name is unique within its namespace, and its qualified name, namespace.name, everywhere. Declare one per module with DefineNamespace.

func DefineNamespace

func DefineNamespace(name string) Namespace

DefineNamespace declares a module's namespace, for its codes and its steps. Call it once per module, from a package-level var.

type Response

type Response struct {
	Code  string `json:"code"`
	Scope Scope  `json:"scope"`
	// Status is the HTTP status, set by the HTTP transport, which assigns one
	// per public code; repeated in the body so it survives a log line or a
	// proxy. A transport with no status leaves it out.
	Status    int            `json:"status,omitzero"`
	Context   []ContextEntry `json:"context,omitempty"`
	Message   string         `json:"message"`
	Details   any            `json:"details,omitzero"`
	RequestID string         `json:"request_id"`
}

Response is the wire form of an error, identical over every transport but for Status.

type Scope

type Scope string

Scope annotates which side is responsible for an error: the person, the calling program, or us.

const (
	// User: the request was well-formed, and the person's input or the state
	// they are acting on refuses it.
	User Scope = "user"
	// Client: the calling program is wrong. The person did nothing to cause it.
	Client Scope = "client"
	// Server: we are wrong, or something we depend on is down.
	Server Scope = "server"
)

type TypedCode

type TypedCode[D any] struct {
	// contains filtered or unexported fields
}

TypedCode is a code whose details have a type, so they are checked where the error is made.

It embeds Code through the unexported alias baseCode, and that is deliberate. The embedded field is then unexported, so no TypedCode literal compiles outside this package — keyed or not — and only DefinePublicCodeWith and DefineInternalCodeWith can pair a code with a details type; yet Code's methods are still promoted. Embedding Code directly would let any package write TypedCode[X]{Code: c} and give a code a details type its documentation, and the OpenAPI built from it, does not have. Do not "simplify" it back.

func DefineInternalCodeWith

func DefineInternalCodeWith[D any](ns Namespace, name string, public TypedCode[D], message string) TypedCode[D]

DefineInternalCodeWith is DefineInternalCode for a public code with typed details: the internal code's details have the same type, so they carry over.

func DefinePublicCodeWith

func DefinePublicCodeWith[D any](ns Namespace, name string, scope Scope, message string) TypedCode[D]

DefinePublicCodeWith is DefinePublicCode for a code whose details have type D, recording D so the contract published from the catalog (OpenAPI, the generated client) types them.

func (TypedCode[D]) Code

func (t TypedCode[D]) Code() Code

Code returns the code underneath the typing: what an *Error's Code field holds, and what to compare one with.

type Violation

type Violation struct {
	Field   string `json:"field"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

Violation is one field-level problem. Field is the request field or engine arg name as the caller sent it; Code is from a small generic set (required, invalid, unknown, unsupported, too_short, too_long, taken).

type Violations

type Violations struct {
	Violations []Violation `json:"violations"`
}

Violations are field-level details: one entry per field the caller got wrong. invalid_request carries them for structural errors, validation_failed for the input's meaning, and a host's own codes may carry them too. Like every details type, they are an object, so the wire says what they are: `{"violations": [...]}`.

func Violate

func Violate(vs ...Violation) Violations

Violate is the details of the violations vs: never a null list, though there are none.

Jump to

Keyboard shortcuts

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