errs

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: MIT Imports: 5 Imported by: 0

README

errs

Opinionated error primitives built on cockroachdb/errors.

Why

  • Canonical error values → HTTP status codes
  • Structured JSON responses with user/developer concerns separated
  • Rich diagnostics (hints, issue links, source location) for logging
  • Configurable sanitization: show stack traces in dev, hide in prod

Usage

Basic
import "github.com/4nd3r5on/errs"

func getUser(id string) error {
    if id == "" {
        return errors.Wrap(errs.ErrMissingArgument, "user_id required")
    }
    // ...
}
HTTP handler
func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {
    user, err := h.svc.GetUser(r.Context(), userID)
    if errs.HandleHTTPErr(r.Context(), w, r, err, nil) {
        return // already responded
    }
    json.NewEncoder(w).Write(user)
}

Default behavior (DefaultHandleHTTPErrOpts):

  • Logs with structured fields (method, path, status, source location)
  • Returns hints + issue links in JSON
  • Sanitizes 5xx messages to http.StatusText(500) (hides stack traces)
  • Uses slog.Default() at ERROR level

Dev override:

errs.HandleHTTPErr(ctx, w, r, err, &errs.HandleHTTPErrOpts{
    SanitizeMessage: false, // show full error text even for 500s
})
Explicit logging
err := doThing()
errs.LogErr(ctx, err,
    errs.LogErrUseLogger(customLogger),
    errs.LogErrUseLogLevel(slog.LevelWarn),
    errs.LogErrUseLoggerArgs("trace_id", traceID),
)

Extracts: source location, details, hints, issue links into structured log fields.

Error → HTTP mapping

ErrInvalidArgument  → 400
ErrUnauthorized     → 401
ErrPermissionDenied → 403
ErrNotFound         → 404
ErrExists/Outdated  → 409
ErrRateLimited      → 429
ErrNotImplemented   → 501
ErrRemoteServiceErr → 502
ErrDeadlineExceeded → 504
// everything else   → 500

Wins:

  • HandleHTTPErr call replaces manual status code mapping + JSON marshaling

Not included:

  • No middleware (use HandleHTTPErr in handlers directly)
  • No i18n (user-facing messages are English error strings)

Documentation

Overview

Package errs provides opinionated error primitives and error handling built on top of cockroachdb/errors.

It defines a small set of canonical error values, maps them to HTTP semantics, and exposes helpers for rendering safe, structured error responses while preserving rich diagnostic context for logging and tracing.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotImplemented = errors.New("not implemented")
	ErrInternal       = errors.New("internal error")

	ErrCanceled         = errors.New("canceled")
	ErrOOM              = errors.New("out of memory")
	ErrDeadlineExceeded = errors.New("deadline exceeded")
	ErrRemoteServiceErr = errors.New("remote service error")
	ErrRateLimited      = errors.New("rate limited")

	ErrInvalidArgument = errors.New("invalid argument")
	ErrMissingArgument = errors.New("missing argument")
	ErrOutOfRange      = errors.New("out of range")

	ErrPermissionDenied = errors.New("permission denied")
	ErrUnauthorized     = errors.New("unauthorized")

	ErrExists   = errors.New("already exists")
	ErrNotFound = errors.New("not found")
	ErrOutdated = errors.New("outdated")
)
View Source
var DefaultHandleHTTPErrOpts = HandleHTTPErrOpts{
	Logger:   slog.Default(),
	LogLevel: slog.LevelError,

	IncludeHints:      true,
	IncludeIssueLinks: true,
	IncludeErrorCode:  true,
	SanitizeMessage:   true,
}
View Source
var DefaultLogErrOptions = LogErrOptions{
	Logger:     slog.Default(),
	LogLevel:   slog.LevelError,
	LoggerArgs: []any{},
	LogDetails: true,
	LogHints:   false,
	LogLinks:   true,
	LogSource:  true,
}

Functions

func GetHTTPCode

func GetHTTPCode(err error) int

func HandleHTTPErr

func HandleHTTPErr(
	ctx context.Context,
	w http.ResponseWriter,
	r *http.Request,
	err error,
	opts *HandleHTTPErrOpts,
) (handled bool)

func LogErr

func LogErr(ctx context.Context, err error, opts ...LogErrOption) (errIsNotNil bool)

Types

type HTTPErrResponse

type HTTPErrResponse struct {
	Error string      `json:"error"`                 // User-facing message
	Code  string      `json:"code,omitempty"`        // Machine-readable error code
	Hints []string    `json:"hints,omitempty"`       // User-facing suggestions
	Links []IssueLink `json:"issue_links,omitempty"` // Bug tracker references
}

HTTPErrResponse is the standard JSON error response body

type HandleHTTPErrOpts

type HandleHTTPErrOpts struct {
	Logger   *slog.Logger
	LogLevel slog.Level

	// Response body control
	IncludeDetails    bool // Developer-facing details (PII risk)
	IncludeHints      bool // User-facing hints
	IncludeIssueLinks bool // Bug tracker links
	IncludeErrorCode  bool // Telemetry key as error code

	// Error handling behavior
	CreateBarrier   bool // Use Handled() to hide internal errors from clients
	SanitizeMessage bool // Only show generic message for 500s
}
type IssueLink struct {
	// URL to the issue on a tracker.
	IssueURL string `json:"issue_url"`
	// Annotation that characterizes a sub-issue.
	Detail string `json:"detail,omitempty"`
}

IssueLink has the same structure as errors.IssueLink but also has additional JSON tags

type LogErrOption

type LogErrOption func(*LogErrOptions)

func LogErrUseLogDetails

func LogErrUseLogDetails(log bool) LogErrOption

func LogErrUseLogHints

func LogErrUseLogHints(log bool) LogErrOption

func LogErrUseLogLevel

func LogErrUseLogLevel(level slog.Level) LogErrOption
func LogErrUseLogLinks(log bool) LogErrOption

func LogErrUseLogSource

func LogErrUseLogSource(log bool) LogErrOption

func LogErrUseLogger

func LogErrUseLogger(logger *slog.Logger) LogErrOption

func LogErrUseLoggerArgs

func LogErrUseLoggerArgs(args ...any) LogErrOption

type LogErrOptions

type LogErrOptions struct {
	Logger     *slog.Logger
	LogLevel   slog.Level
	LoggerArgs []any
	LogDetails bool
	LogHints   bool
	LogLinks   bool
	LogSource  bool
}

Jump to

Keyboard shortcuts

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