An error package for Go v0.3.2

An error that knows the path it took.

errors gives every error a tag, a stack trace and a route: the chain of functions from the one your test called down to the one that failed. A test checks the route, so it passes only when the error happened where you designed it to happen.

Get started GitHub

go get github.com/rm4n0s/errors
func TestCreateUser_RejectsDuplicateEmail(t *testing.T) {
    repo := repository.NewFake(withExistingUser("a@b.c"))
    svc := service.NewUserService(repo)

    err := svc.CreateUser("a@b.c")

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

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

The route reads from the caller to the failure and ends with the tag: UserService.CreateUser->UserRepository.Save.UserAlreadyExists.

0 dependencies

The package imports the standard library of Go and nothing else.

3 constructors

New, NewErr and NewErrf make an error and record the call stack at their line.

32 frames

of the call stack are kept each time a stack is recorded.

15 projects

of this site have it in their go.mod. That is every other project here, Glutter and Emetos among them.

  • A route for every error

    The stack of an error becomes one string: the functions from the one you called down to the one that failed, with the tag at its end. HasRoute checks it in a test.

  • Tags, not messages

    An error is identified by its tag, a string such as UserAlreadyExists. Code branches on the tag, and errors.Is compares tags. The message is for people and may change.

  • From the log back to a test

    Logged with log/slog, an error writes its tag, message, route, metadata and stack frames. The logged object unmarshals into ErrorJson, and a test replays it.

Say what each function cannot do

A tag names one thing that a function can’t do. With test-driven development you design a monolithic application this way, by saying for each function which errors it should raise. The error is made once, in the function that fails, and goes up unchanged.

  • New takes a tag, a message and pairs of metadata, and records the call stack by itself
  • The functions above write return err. The route already shows who called whom, so nothing is wrapped
  • An error from outside your project is tagged once with NewErr, where it first appears in your code
// package repository
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 // the tag, the metadata and the stack stay
    }
    return nil
}

What a route gives you

Each example was run with version 0.3.2, and the output beside it is what the run printed.

Route

The path is a string you can read

Frames run from the outermost to the innermost, joined by ->. A method is Struct.Func, a function is Func, and the tag comes last. Package names never appear.

  • Route(), HasRoute() and ToJson() stop at the function that called them, so in a test the route starts just below the test function
  • HasRoute is a substring check. Give it the path from the function you call down to .Tag
  • When a check fails, print Route() to see the path that the error really took
err := svc.CreateUser("alice@example.com")
appErr, _ := errors.FromError(err)

fmt.Println(appErr.Route())
fmt.Println(appErr.Tag, appErr.Metadata)

// Output:
// UserService.CreateUser->UserRepository.Save.UserAlreadyExists
// UserAlreadyExists map[email:alice@example.com]

Logs

An error logs itself whole

*errors.Error implements slog.LogValuer. Give it to log/slog as an attribute, as in logger.Error("create user failed", "err", err), and the entry has the tag, the message, the route, the metadata and the stack frames. Beside is the err of such an entry, from the JSON handler of slog.

  • The route is trimmed at the function that called the logger
  • The keys match the fields of errors.ErrorJson, so the entry unmarshals straight into it
  • Without slog, ToJson() gives the same object
{
  "Tag": "UserAlreadyExists",
  "Message": "a user with this email already exists",
  "Route": "UserService.CreateUser->UserRepository.Save.UserAlreadyExists",
  "Metadata": {
    "email": "alice@example.com"
  },
  "StackFrames": [
    {
      "FuncName": "Save",
      "StructName": "UserRepository",
      "PackageName": "shop"
    },
    {
      "FuncName": "CreateUser",
      "StructName": "UserService",
      "PackageName": "shop"
    }
  ]
}

Goroutines

The route crosses a goroutine

The call stack of a goroutine does not have the function that started it. Wrap the work with errors.Async before you hand it off, and the route continues with the caller of Async, as if the function had been called directly. Without Async the route starts at the goroutine’s own function.

  • AsyncRecover does the same and turns a panic in the goroutine into an error with the tag errors.TagPanic. Its route ends at the function that panicked
  • With errgroup, pass the result straight in: g.Go(errors.Async(fn))
  • Frames of the Go runtime, such as goexit, never appear in a route
func (s *Service) Run() error {
    ch := make(chan error, 1)
    // Call Async in the parent, run the result in the child.
    work := errors.Async(func() error { return s.worker() })
    go func() { ch <- work() }()
    return <-ch
}

// The route of the error that Run returns:
// Service.Run->Service.Run.func1->Service.worker.WorkFailed

Foreign errors

Tag an error from outside, once

NewErr takes an error of the standard library, of a database driver or of any other package. The message of that error becomes the message, and Unwrap returns the original, so errors.Is still finds it. NewErrf does the same from a format, as fmt.Errorf does.

  • The package has Is, As, Unwrap and Join of the standard library, so you import only this one
  • SetMetadata merges pairs into the metadata of an error, and RemoveMetadata deletes keys
func (r *UserRepository) Find(id int) (*User, error) {
    u, err := r.db.QueryRow(id)
    if err != nil {
        return nil, errors.NewErr("UserQueryFailed", err).
            SetMetadata("userID", id)
    }
    return u, nil
}

// In the caller:
_, err := repo.Find(7)
e, _ := errors.FromError(err)
fmt.Println(e.Route())
fmt.Println(e.Message, e.Metadata)
fmt.Println(errors.Is(err, sql.ErrNoRows))

// Output:
// UserRepository.Find.UserQueryFailed
// sql: no rows in result set map[userID:7]
// true

Stack trace

The whole stack, when you want it

fmt.Printf("%+v", err) prints the message and then the stack trace, with the file and the line of each frame. %v and %s print only the message.

  • StackTrace() returns the same trace as a string
  • StackFrames(true) returns the frames as values, innermost first, with the frames of the Go runtime
a user with this email already exists
shop.(*UserRepository).Save
    shop/users.go:21
shop.(*UserService).CreateUser
    shop/users.go:46
main.main
    shop/cmd/trace/main.go:10
runtime.main
    runtime/proc.go:302
runtime.goexit
    runtime/asm_amd64.s:1264

The rest of the package

It is small. These are the other calls that you will use.

  • errors.All

    Returns every *errors.Error inside a joined or wrapped error, outermost first. Use it after errors.Join, when several goroutines can fail.

  • Is, by tag

    Two errors are the same for errors.Is when their tags are the same. A sentinel is a struct literal: &errors.Error{Tag: "UserNotFound"}.

  • Metadata

    Pairs of a key and a value, given to New in one call: "count", n, "max", max. They are logged with the error and come back in a replay.

  • ToJson and FromJson

    ToJson() gives an ErrorJson to marshal yourself, and errors.FromJson makes an *errors.Error of it again. The route survives the round trip.

Which call, when

Every error is tagged once, at the place where it first appears in your code. After that it travels up as the same value.

Where the error comes fromWhat to write
Your own function finds the failureerrors.New("TooManyItems", "too many items", "count", n)
A package outside your project returned iterrors.NewErr("UserQueryFailed", err)
The same, with a message of your own around iterrors.NewErrf("UserQueryFailed", "user %d: %w", id, err)
A function of your project returned itreturn err
A sentinel, to compare with errors.Is&errors.Error{Tag: "UserNotFound"}

The rules are from AI_GUIDE.md, which the repository has for AI coding assistants: the whole API, seven rules and a checklist.

Replay a bug from your logs

Paste the entry of the log into a test. The test fails until your code makes the same error on the same route as production did. Then the bug is in a test, and you can fix it.

  • ErrorJson has Route() and HasRoute() too, so the logged path is there before anything runs
  • The metadata of the entry gives the input that failed
  • After json.Unmarshal, a number in the metadata is a float64
func TestReproduceIssue482(t *testing.T) {
    var entry struct {
        Err errors.ErrorJson `json:"err"`
    }
    // rawLogEntry is pasted from the log.
    err := json.Unmarshal([]byte(rawLogEntry), &entry)
    if err != nil {
        t.Fatal(err)
    }
    logged := entry.Err
    t.Logf("original failure path: %s", logged.Route())

    email, _ := logged.Metadata["email"].(string)
    svc := service.NewUserService(productionLikeRepo)
    err = svc.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)
    }
}

Where it is used

The 15 other projects of this site all have the package in their go.mod. These are six of them.

What errors does not do

Better to read it here than to find it out.

  • FromError is a plain type assertion and does not unwrap. An error that was wrapped with fmt.Errorf("...: %w", err) is not found by it. errors.All finds it.
  • A route has the names of functions and types and no package names, and HasRoute is a substring check.
  • The route is recorded where the constructor runs. A helper that makes the error appears in the route, and a package-level var ErrX = errors.New(...) has the route init.Tag.
  • An *Error is not safe for concurrent use. Do not call SetMetadata, RemoveMetadata or SetMessage on an error that another goroutine can still reach.
  • NewErr(tag, nil) panics. Call it inside if err != nil.
  • It may not add much to a small service, where two or three functions call each other. It is made for monolithic applications with long chains of conditional logic.

Under the hood#

This package gives errors that know their stack trace, as other packages do, with one difference: the methods Route() and HasRoute() let a unit test verify that an error happened along a specific path of execution.

With test-driven development, this lets you design a monolithic application by saying, for each function, which errors it should raise.

New, NewErr and NewErrf call runtime.Callers at the line where they run and keep the program counters. The names of the functions are looked up later, when you ask for the route, the frames or the JSON. Route() walks the frames from the function that made the error outwards and stops at the function that called Route(), so a test sees the path under the test function and nothing above it.

Async records the stack of the function that hands the work off. When the wrapped function returns an error that was made inside it, the frames of the goroutine above the wrapper are replaced with that stack.

Errors log themselves through log/slog, and ToJson() turns an error into JSON. You can take an error from your logs and replay it in an integration test, to reproduce the bug.

The ideas behind it are in two posts of my blog: Error Handling Challenge and Can’t Driven Development.

Kind
Library
Language
Go
License
MIT
Version
v0.3.2

Guides for errors

Add it to your module

The package needs Go 1.26.3 or newer, the version of its go.mod, and no other module. Its New takes a tag and a message, so it is not the errors.New of the standard library.

Test the path of an error in Go Source on GitHub

# Add the package to your module
$ go get github.com/rm4n0s/errors
# Check the routes of your errors with your tests
$ go test ./...
# Or run the example of the repository first
$ git clone https://github.com/rm4n0s/errors && cd errors
$ go run ./examples/challenge