errors

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 9 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.

README

errors

Why

This package provides stack-trace-aware errors, similar to other error-handling libraries — but with one key difference: the Route() and HasRoute() methods let you write unit tests that verify not just that an error occurred, but that it occurred along a specific execution path.
Combined with test-driven development, this allows you to design a monolithic application by defining, for each function, the errors it should raise — effectively driving your software's architecture through its error paths.
You can read more about the problem this package addresses in Error Handling Challenge, and about the underlying theory of architecting software around its errors in Can't Driven Development.
Errors log themselves through log/slog, and a ToJson() method serializes an error to JSON. This lets you take an error captured in your logs and replay it in an integration test, making it straightforward to reproduce and fix the underlying bug.

Usage

AI coding assistants: read AI_GUIDE.md before using this package.

Define errors close to where they happen

Give each function a Tag for the errors it can produce. New captures the call stack automatically.

package repository

import "github.com/rm4n0s/errors"

func (r *UserRepository) Save(user *User) error {
    if exists, _ := r.db.EmailExists(user.Email); exists {
        return errors.New("UserAlreadyExists", "a user with this email already exists", "email", user.Email)
    }
    return r.db.Insert(user)
}
package service

func (s *UserService) CreateUser(email string) error {
    user := &User{Email: email}
    if err := s.repo.Save(user); err != nil {
        return err // bubble up untouched — Tag, Metadata and the stack stay intact
    }
    return nil
}
Test that an error came from a specific path

This is the part other error packages don't give you: with this you don't test only a failure but also the execution path followed to the specific failure.

func TestCreateUser_RejectsDuplicateEmail(t *testing.T) {
    repo := repository.NewFake(withExistingUser("[email protected]"))
    svc := service.NewUserService(repo)

    err := svc.CreateUser("[email protected]")

    appErr, ok := errors.FromError(err)
    if !ok {
        t.Fatalf("expected *errors.Error, got %T", err)
    }

    // Not just "an error happened" — it happened in Save, called from CreateUser.
    if !appErr.HasRoute("UserService.CreateUser->UserRepository.Save.UserAlreadyExists") {
        t.Errorf("unexpected failure path: %s", appErr.Route())
    }
}

This may not add much value for microservices, where only two or three functions call into each other. But for monolithic applications with long chains of conditional logic — as is common in ERP-style systems — it becomes crucial.

Reproduce a production bug from your logs

*errors.Error implements slog.LogValuer, so logging it with log/slog writes the tag, message, route, metadata and stack frames. The keys match the fields of ErrorJson, so the logged object can be unmarshaled straight back into it.

logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Error("create user failed", "err", err)
// {"time":"...","level":"ERROR","msg":"create user failed","err":{"Tag":"UserAlreadyExists","Message":"...",
//  "Route":"UserService.CreateUser->UserRepository.Save.UserAlreadyExists","Metadata":{"email":"..."},"StackFrames":[...]}}
func TestReproduceIssue482(t *testing.T) {
    var entry struct {
        Err errors.ErrorJson `json:"err"`
    }
    if err := json.Unmarshal([]byte(rawLogEntry), &entry); err != nil { // pasted from the log
        t.Fatal(err)
    }
    logged := entry.Err
    t.Logf("original failure path: %s", logged.Route())

    email, _ := logged.Metadata["email"].(string)
    err := service.NewUserService(productionLikeRepo).CreateUser(email)

    appErr, ok := errors.FromError(err)
    if !ok || appErr.Tag != logged.Tag || !appErr.HasRoute(logged.Route()) {
        t.Fatalf("bug not reproduced: want %s, got %v", logged.Route(), err)
    }
}

Without slog, use appErr.ToJson() and marshal the result yourself, and errors.FromJson(logged) to turn it back into an *errors.Error.

Keep the route across goroutines

A goroutine's call stack does not contain the function that started it. Wrap the work with errors.Async before handing it off, and the route continues with the caller of Async, exactly as if the function had been called directly:

func (s *Service) Run() error {
    ch := make(chan error, 1)
    work := errors.Async(func() error { return s.worker() }) // call it in the parent
    go func() { ch <- work() }()                             // run it in the child, or g.Go(work) with errgroup
    return <-ch
}
// Route: Service.Run->Service.Run.func1->Service.worker.WorkFailed

For a worker pool, call errors.Async where the job is submitted. Without Async the route starts at the goroutine's own function. Frames of the Go runtime, such as goexit, never appear in a route.

errors.AsyncRecover does the same and also turns a panic in the goroutine into an error with the tag errors.TagPanic, whose route ends at the function that panicked.

When several goroutines can fail, combine their errors with errors.Join and read them back with errors.All, which returns every *errors.Error inside a joined or wrapped error:

for _, e := range errors.All(err) {
    fmt.Println(e.Route())
}
Print the stack trace

fmt.Printf("%+v", err) prints the message followed by the stack trace. %v and %s print only the message.

Documentation

Index

Constants

View Source
const TagPanic = "Panic"

TagPanic is the Tag of the error that AsyncRecover returns for a panic.

Variables

View Source
var (
	Is     = errors.Is
	As     = errors.As
	Unwrap = errors.Unwrap
	Join   = errors.Join
)

Functions

func Async added in v0.3.0

func Async(fn func() error) func() error

Async carries the route across a goroutine boundary. Call it in the goroutine that hands the work off, and run the returned function in any goroutine:

work := errors.Async(func() error { return s.save(u) })
go func() { ch <- work() }() // or g.Go(work) with errgroup

An *Error created while fn runs and returned by it gets the call stack of the Async call in place of the stack of the goroutine that ran it, so its route reads as if fn had been called directly where Async was called.

func AsyncRecover added in v0.3.0

func AsyncRecover(fn func() error) func() error

AsyncRecover is Async that also recovers a panic in fn and returns it as an *Error with the Tag TagPanic. Its route ends at the function that panicked. The message is the panic value, and when that value is an error it becomes OriginalErr.

Types

type Error

type Error struct {
	Tag         string
	Message     string
	Metadata    map[string]any
	OriginalErr error
	// contains filtered or unexported fields
}

func All added in v0.3.0

func All(err error) []*Error

All returns every *Error in the tree of err, outermost first. It follows both Unwrap() error and Unwrap() []error, so it finds the errors inside errors.Join and fmt.Errorf("%w").

func FromError

func FromError(err error) (*Error, bool)

func FromJson

func FromJson(errj ErrorJson) *Error

func New

func New(tag, message string, metadata ...any) *Error

func NewErr

func NewErr(tag string, err error) *Error

func NewErrf

func NewErrf(tag, format string, a ...any) *Error

func (*Error) Error

func (err *Error) Error() string

func (*Error) Format added in v0.2.0

func (e *Error) Format(s fmt.State, verb rune)

Format implements fmt.Formatter. %+v prints the message followed by the stack trace.

func (*Error) HasRoute

func (e *Error) HasRoute(route string) bool

func (*Error) Is

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

func (*Error) LogValue added in v0.2.0

func (e *Error) LogValue() slog.Value

LogValue implements slog.LogValuer. The keys match the ErrorJson fields, so a logged error can be unmarshaled into ErrorJson and replayed with FromJson.

func (*Error) RemoveMetadata

func (err *Error) RemoveMetadata(keys ...string) *Error

func (*Error) Route

func (e *Error) Route() string

func (*Error) SetMessage

func (err *Error) SetMessage(msg string) *Error

func (*Error) SetMetadata

func (err *Error) SetMetadata(metadata ...any) *Error

func (*Error) StackFrames

func (e *Error) StackFrames(all bool) []StackFrame

func (*Error) StackTrace

func (e *Error) StackTrace() string

func (*Error) ToJson

func (e *Error) ToJson() *ErrorJson

func (*Error) Unwrap

func (err *Error) Unwrap() error

type ErrorJson

type ErrorJson struct {
	Tag         string
	Message     string
	OriginalErr string
	Metadata    map[string]any
	StackFrames []StackFrame
}

func (*ErrorJson) HasRoute

func (e *ErrorJson) HasRoute(route string) bool

func (*ErrorJson) Route

func (e *ErrorJson) Route() string

type StackFrame

type StackFrame struct {
	FuncName    string
	StructName  string
	PackageName string
}

Directories

Path Synopsis
examples
challenge command
tests

Jump to

Keyboard shortcuts

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