errors

package
v0.4.5 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 2 Imported by: ? modules, 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.

Documentation

Overview

Package errors defines the error taxonomy shared by every frontend of the kit: one coded error drives the CLI exit code, the HTTP status code, and the MCP JSON-RPC error code alike, so transport implementations never need to interpret command-specific error strings.

Two layers of identity ride on one error:

  • Kind — the coarse taxonomy (invalid_input, not_found, …). It is what frontends translate into an HTTP status / CLI exit code / JSON-RPC code. Stable and small; frontends switch on it.
  • Code — an optional free-form business identifier ("USER_NOT_FOUND", "QUOTA_EXCEEDED"). It never affects transport mapping; it is carried verbatim to the caller so clients can branch on domain semantics without parsing messages.

On top of those, an error may carry Detail (structured key/value context) and an explicit Status override (HTTP only). The simplest possible handler error — errors.New("boom") or fmt.Errorf(...) — needs none of this: it is classified KindInternal and rendered with its message. Richness is opt-in and composes:

return errors.New("boom")                                  // 最简
return errs.NotFound("user %s", id)                        // 带 Kind
return errs.NotFound("user %s", id).                       // 带业务标识符
       WithCode("USER_NOT_FOUND").WithDetail("user_id", id)
return errs.Wrap(errs.KindUnavailable, err).WithCode("DB_DOWN")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cause

func Cause(err error) error

Cause unwraps coded errors and returns the innermost known cause.

func Code added in v0.4.2

func Code(err error) string

Code returns the business identifier of the first coded layer, or "".

func Detail added in v0.4.2

func Detail(err error) map[string]any

Detail returns the structured detail of the first coded layer (nil if none).

func Errorf

func Errorf(kind Kind, format string, a ...any) error

Errorf builds a coded error with a formatted message.

func ExitCode

func ExitCode(k Kind) int

ExitCode maps a Kind to a CLI process exit code.

func HTTPStatus

func HTTPStatus(k Kind) int

HTTPStatus maps a Kind to its natural HTTP status code.

func JSONRPCCode

func JSONRPCCode(k Kind) int

JSONRPCCode maps a Kind to a JSON-RPC 2.0 error code. Standard codes are negative; application-defined server errors live in the -32000..-32099 range both JSON-RPC and MCP reserve for this purpose.

func New

func New(kind Kind, msg string) error

New builds a coded error with no cause.

func RPCCodeFor added in v0.4.2

func RPCCodeFor(err error) int

RPCCodeFor returns the JSON-RPC error code for an error (Kind-derived).

func StatusFor added in v0.4.2

func StatusFor(err error) int

StatusFor returns the HTTP status for an error: the explicit Status override when set, otherwise the status derived from its Kind. A non-coded error classifies as KindInternal (500).

func Wrap

func Wrap(kind Kind, cause error) error

Wrap builds a coded error whose message is the cause's.

func WrapMsg

func WrapMsg(kind Kind, cause error, msg string) error

WrapMsg builds a coded error with both a message and a cause.

Types

type Body added in v0.4.2

type Body struct {
	Error  string         `json:"error"`
	Kind   Kind           `json:"kind,omitempty"`
	Code   string         `json:"code,omitempty"`
	Detail map[string]any `json:"detail,omitempty"`
}

Body is the enriched machine-readable form of an error, shared by every frontend so HTTP bodies, CLI machine-mode stderr and MCP _meta agree on one shape. The flat Error string keeps the pre-v0.4.2 HTTP contract ({"error":"<message>"}) intact for existing clients; Kind/Code/Detail are additive.

func ErrorBody added in v0.4.2

func ErrorBody(err error) Body

ErrorBody projects any error into the shared Body. A nil error yields the zero Body. A plain (non-coded) error yields just its message under KindInternal.

type CodedError

type CodedError struct {
	Kind    Kind
	Message string
	// Code is a free-form business identifier (e.g. "USER_NOT_FOUND").
	// It is carried verbatim to callers and never affects transport mapping.
	Code string
	// Detail is structured context attached to the error. It is rendered
	// into the HTTP error body and the MCP result _meta as-is.
	Detail map[string]any
	// Status overrides the HTTP status derived from Kind (0 = derive).
	// It only affects the HTTP frontend.
	Status int
	// contains filtered or unexported fields
}

CodedError wraps a cause with a Kind, an optional message, an optional business Code, structured Detail and an optional HTTP Status override. Its methods are chainable and return the same pointer, so a handler can build a rich error in one expression.

func Canceled added in v0.4.2

func Canceled(format string, a ...any) *CodedError

func Conflict added in v0.4.2

func Conflict(format string, a ...any) *CodedError

func Err added in v0.4.2

func Err(kind Kind, format string, a ...any) *CodedError

Err builds a chainable *CodedError with a formatted message and no cause. It is the constructor meant for one-expression rich errors:

return errs.Err(errs.KindConflict, "%s exists", name).WithCode("DUPLICATE")

func Forbidden added in v0.4.2

func Forbidden(format string, a ...any) *CodedError

func From added in v0.4.2

func From(err error) *CodedError

From extracts the first *CodedError in the chain, or nil when the error carries no coded layer (a plain errors.New / fmt.Errorf). Frontends use it to read Code/Detail/Status without re-walking the chain.

func Internal added in v0.4.2

func Internal(format string, a ...any) *CodedError

func InvalidInput added in v0.4.2

func InvalidInput(format string, a ...any) *CodedError

Per-Kind shortcuts. Each returns a chainable *CodedError so the common "kind + message + optional code/detail" reads in one line.

func NotFound added in v0.4.2

func NotFound(format string, a ...any) *CodedError

func Unauthorized added in v0.4.2

func Unauthorized(format string, a ...any) *CodedError

func Unavailable added in v0.4.2

func Unavailable(format string, a ...any) *CodedError

func (*CodedError) Error

func (e *CodedError) Error() string

func (*CodedError) Unwrap

func (e *CodedError) Unwrap() error

Unwrap exposes the cause for errors.Is / errors.As.

func (*CodedError) WithCause added in v0.4.2

func (e *CodedError) WithCause(err error) *CodedError

WithCause attaches (or replaces) the underlying cause. Chainable.

func (*CodedError) WithCode added in v0.4.2

func (e *CodedError) WithCode(code string) *CodedError

WithCode attaches a free-form business identifier. Chainable.

func (*CodedError) WithDetail added in v0.4.2

func (e *CodedError) WithDetail(key string, value any) *CodedError

WithDetail attaches one structured detail entry. Chainable; a nil Detail map is created on first use.

func (*CodedError) WithDetails added in v0.4.2

func (e *CodedError) WithDetails(m map[string]any) *CodedError

WithDetails merges a batch of structured detail entries. Chainable.

func (*CodedError) WithStatus added in v0.4.2

func (e *CodedError) WithStatus(status int) *CodedError

WithStatus overrides the HTTP status derived from Kind (HTTP only). Chainable.

type Kind

type Kind string

Kind classifies an error. Frontends translate a Kind into their own error representation via HTTPStatus, ExitCode and JSONRPCCode.

const (
	// KindInvalidInput means the caller provided malformed or invalid
	// arguments (missing required fields, failed validation, bad enums).
	KindInvalidInput Kind = "invalid_input"
	// KindUnauthorized means the caller must authenticate before retrying.
	KindUnauthorized Kind = "unauthorized"
	// KindForbidden means the caller authenticated but lacks permission.
	KindForbidden Kind = "forbidden"
	// KindNotFound means the target of the operation does not exist.
	KindNotFound Kind = "not_found"
	// KindConflict means the operation collides with existing state.
	KindConflict Kind = "conflict"
	// KindCanceled means the operation was canceled by the caller.
	KindCanceled Kind = "canceled"
	// KindUnavailable means a dependency is temporarily down.
	KindUnavailable Kind = "unavailable"
	// KindInternal is the fallback for unclassified failures.
	KindInternal Kind = "internal"
	// KindNone is what Classify returns for a nil error.
	KindNone Kind = ""
)

func Classify

func Classify(err error) Kind

Classify walks the error chain and returns the first coded Kind. Unclassified non-nil errors fall back to KindInternal; a nil error is KindNone.

Jump to

Keyboard shortcuts

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