Documentation
¶
Overview ¶
Package errs provides a single, transport-agnostic error type with stable codes, their HTTP statuses (grpcserver maps them to gRPC codes), errors of invalid input fields, and automatic redaction of secrets in user-facing messages. It depends on the standard library only.
An *Error carries a machine-readable Code, an optional Title, a human Message (the "detail"), and optional Args used for i18n. It implements the standard error interface and unwraps to any underlying cause, so it composes with errors.Is/errors.As. The JSON shape is small and stable ({"code","title","detail","fields"}) so an *Error can be returned directly to API clients.
Codes ¶
Code is a stable classification whose integer values are aligned with google.golang.org/grpc/codes, so gRPC mapping is an identity and HTTP mapping is a small lookup table. Each code has a snake_case String (e.g. "invalid_argument") used as the wire "code" and as the default i18n key, and an HTTPStatus. ErrorType returns the same string, so otel.SetError writes it as the span's error.type. The canonical codes are OK, Canceled, Unknown, InvalidArgument, DeadlineExceeded, NotFound, AlreadyExists, PermissionDenied, ResourceExhausted, FailedPrecondition, Aborted, OutOfRange, Unimplemented, Internal, Unavailable, DataLoss, and Unauthenticated.
Creating errors ¶
New wraps an existing error, Newf formats a fresh message, and Wrapf wraps a cause behind a formatted prefix. The call site (function and file:line) is captured for logging. Chain WithTitle, WithMessageID, and WithArgs to enrich an error:
if w == nil {
return errs.Newf(errs.NotFound, "widget %d not found", id).
WithTitle("widget not found").
WithMessageID("widget.not_found").
WithArgs(map[string]any{"id": id})
}
// Wrap a low-level cause behind a stable code:
if err := db.QueryRow(...); err != nil {
return errs.Wrapf(errs.Internal, err, "load widget %d", id)
}
Normalizing and inspecting ¶
From normalizes any error into an *Error (an unrecognized error becomes Internal), and Is reports whether an error carries a given Code:
e := errs.From(err) // always an *errs.Error (or nil)
if errs.Is(err, errs.NotFound) { // code-aware check
...
}
Encoding (HTTP) ¶
Encode renders the error as JSON and returns (data, contentType, error), satisfying the web encoder contract. It runs the detail through Sanitize, so secrets never leak to clients. HTTPStatus gives the response status:
body, contentType, _ := e.Encode()
w.Header().Set("Content-Type", contentType)
w.WriteHeader(e.HTTPStatus())
w.Write(body)
Field errors ¶
FieldErrors collects the invalid fields of an input, so a client sees them all at once. Add skips a nil error; Err returns nil when nothing was added, else an InvalidArgument *Error whose Fields list the fields. NewFieldError builds the same error for one field. Every field error has the title "data validation error" and the detail "validation failed":
var fe errs.FieldErrors
id, err := uuid.Parse(q.Get("id"))
fe.Add("id", err)
from, err := time.Parse(time.DateOnly, q.Get("from"))
fe.Add("from", err)
if err := fe.Err(); err != nil {
return err // 400: {"fields":[{"field":"id","error":"..."}, ...]}
}
The package validate checks struct tags and reports through the same FieldErrors.
Sanitization ¶
Sanitize redacts common secret patterns (password/token/secret/api_key in key=value and JSON forms) and truncates to MaxMessageLen on a UTF-8 boundary. Encode applies it automatically; call it directly for any other string bound for logs or responses.
i18n ¶
An *Error is localized by the i18n package using MessageID (or, when unset, CodeStr) as the lookup key and Args as template data; see that package's TranslateError.
Example ¶
A handler returns an *Error with a stable code; the transport answers with the status of the code and the JSON of the error.
package main
import (
"fmt"
"github.com/assanoff/skit/errs"
)
func main() {
err := errs.Newf(errs.NotFound, "widget %d not found", 42).
WithTitle("widget not found")
body, contentType, _ := err.Encode()
fmt.Println(err.HTTPStatus(), contentType)
fmt.Println(string(body))
}
Output: 404 application/json {"code":"not_found","title":"widget not found","detail":"widget 42 not found"}
Index ¶
- Constants
- func Is(err error, code Code) bool
- func Sanitize(msg string) string
- type Code
- type Error
- func (e *Error) Encode() ([]byte, string, error)
- func (e *Error) Error() string
- func (e *Error) ErrorType() string
- func (e *Error) HTTPStatus() int
- func (e *Error) Unwrap() error
- func (e *Error) WithArgs(args map[string]any) *Error
- func (e *Error) WithMessageID(id string) *Error
- func (e *Error) WithTitle(title string) *Error
- type FieldError
- type FieldErrors
Examples ¶
Constants ¶
const MaxMessageLen = 1024
MaxMessageLen bounds the length of a sanitized message to keep logs and API responses tidy.
Variables ¶
This section is empty.
Functions ¶
func Sanitize ¶
Sanitize redacts common secret patterns and truncates the message to MaxMessageLen on a UTF-8 boundary. It is safe to call on any string.
Example ¶
Sanitize redacts secrets in a message bound for a client or a log.
package main
import (
"fmt"
"github.com/assanoff/skit/errs"
)
func main() {
fmt.Println(errs.Sanitize(`login failed: password=hunter2 {"token":"abc"}`))
}
Output: login failed: password=*** {"token":"***"}
Types ¶
type Code ¶
type Code uint32
Code is a stable, transport-agnostic error classification. Its integer values are intentionally aligned with google.golang.org/grpc/codes so that gRPC mapping is an identity and HTTP mapping is a small lookup table.
const ( OK Code = 0 Canceled Code = 1 Unknown Code = 2 InvalidArgument Code = 3 DeadlineExceeded Code = 4 NotFound Code = 5 AlreadyExists Code = 6 PermissionDenied Code = 7 ResourceExhausted Code = 8 FailedPrecondition Code = 9 Aborted Code = 10 OutOfRange Code = 11 Unimplemented Code = 12 Internal Code = 13 DataLoss Code = 15 Unauthenticated Code = 16 )
Canonical error codes, value-aligned with gRPC status codes.
func (Code) HTTPStatus ¶
HTTPStatus maps the code to an HTTP status code.
type Error ¶
type Error struct {
Code Code `json:"-"`
CodeStr string `json:"code"`
Title string `json:"title,omitempty"`
Message string `json:"detail"`
Fields FieldErrors `json:"fields,omitempty"`
Args map[string]any `json:"-"`
// MessageID is an optional i18n message key. When set it overrides CodeStr as
// the lookup key the i18n package uses to localize Message; Args supply the
// template data. Left empty, translation falls back to CodeStr.
MessageID string `json:"-"`
// contains filtered or unexported fields
}
Error is the canonical application error.
The JSON shape is intentionally small and stable so it can be returned directly to API clients:
{"code":"not_found","title":"...","detail":"widget 42 not found","fields":[...]}
func From ¶
From normalizes any error into an *Error. If err already is (or wraps) an *Error it is returned as-is; otherwise it becomes an Internal error.
Example ¶
From turns any error into an *Error: one it wraps is returned as is, any other becomes Internal.
package main
import (
"errors"
"fmt"
"github.com/assanoff/skit/errs"
)
func main() {
known := fmt.Errorf("query: %w", errs.Newf(errs.AlreadyExists, "name taken"))
unknown := errors.New("connection reset")
fmt.Println(errs.From(known).Code, errs.From(known).HTTPStatus())
fmt.Println(errs.From(unknown).Code, errs.From(unknown).HTTPStatus())
}
Output: already_exists 409 internal 500
func New ¶
New creates an *Error with the given code, wrapping err. The message is taken from err. The call site (function and file:line) is captured for logging.
func NewFieldError ¶ added in v0.14.0
NewFieldError returns an InvalidArgument *Error for one invalid field. It wraps err.
func Wrapf ¶
Wrapf wraps err with a code and a formatted message that prefixes the cause.
Example ¶
Wrapf puts a low-level cause behind a stable code: errs.Is checks the code, errors.Is still finds the cause.
package main
import (
"errors"
"fmt"
"io"
"github.com/assanoff/skit/errs"
)
func main() {
err := errs.Wrapf(errs.Unavailable, io.ErrUnexpectedEOF, "load widget %d", 42)
fmt.Println(err)
fmt.Println(errs.Is(err, errs.Unavailable), errors.Is(err, io.ErrUnexpectedEOF))
}
Output: github.com/assanoff/skit/errs_test.ExampleWrapf: unavailable: load widget 42: unexpected EOF true true
func (*Error) Encode ¶
Encode renders the error as JSON, redacting any secrets in the detail. It satisfies the web encoder contract: (data, contentType, error).
func (*Error) ErrorType ¶ added in v0.14.0
ErrorType returns the code string, such as "internal". otel.SetError writes it as the span's error.type: semconv.ErrorType finds the method anywhere in the error chain, so a wrapped *Error is classified by its code too.
func (*Error) HTTPStatus ¶
HTTPStatus returns the HTTP status code for this error.
func (*Error) WithMessageID ¶
WithMessageID sets the i18n lookup key and returns the error for chaining.
type FieldError ¶
FieldError describes a single invalid input field.
type FieldErrors ¶ added in v0.14.0
type FieldErrors []FieldError
FieldErrors collects the invalid fields of an input, so a client sees them all at once.
Example ¶
FieldErrors collects every invalid field of an input, so the client sees them all at once; Add skips a nil error.
package main
import (
"errors"
"fmt"
"strconv"
"github.com/assanoff/skit/errs"
)
func main() {
var fe errs.FieldErrors
_, err := strconv.Atoi("ten")
fe.Add("limit", err)
_, err = strconv.Atoi("0")
fe.Add("offset", err)
fe.Add("sort", errors.New("unknown field \"color\""))
body, _, _ := errs.From(fe.Err()).Encode()
fmt.Println(string(body))
}
Output: {"code":"invalid_argument","title":"data validation error","detail":"validation failed","fields":[{"field":"limit","error":"strconv.Atoi: parsing \"ten\": invalid syntax"},{"field":"sort","error":"unknown field \"color\""}]}
func (*FieldErrors) Add ¶ added in v0.14.0
func (fe *FieldErrors) Add(field string, err error)
Add records err for field. A nil err records nothing, so the result of a parse can be added unchecked.
func (*FieldErrors) Err ¶ added in v0.14.0
func (fe *FieldErrors) Err() error
Err returns nil when no field is recorded, else an InvalidArgument *Error whose Fields are fe. The result is an error, not an *Error: an empty list gives a true nil, never a typed nil that compares non-nil.