Test the path of an error in Go

Use the errors package to write a test that checks which functions an error went through, and to replay an error from your logs.

4 min to read

A usual test of a failure asks one question: did the function return an error? In a large application that is not enough. The same error can come from several places, and a test that passes for the wrong reason hides a bug.

The errors package gives every error a route: the chain of functions from the one your test called down to the one that failed. A test can check that route.

Install#

go get github.com/rm4n0s/errors

Define errors where they happen#

Give each error a tag when you create it. New takes the tag, a message, and pairs of metadata, and captures the call stack by itself.

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)
}

The functions above it return the error untouched. The tag, the metadata and the stack stay as they are.

package service

func (s *UserService) CreateUser(email string) error {
    user := &User{Email: email}
    if err := s.repo.Save(user); err != nil {
        return err
    }
    return nil
}

Test the route#

FromError gives you the *errors.Error back, and HasRoute checks the path.

func TestCreateUser_RejectsDuplicateEmail(t *testing.T) {
    repo := repository.NewFake(withExistingUser("alice@example.com"))
    svc := service.NewUserService(repo)

    err := svc.CreateUser("alice@example.com")

    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())
    }
}

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

This may not add much for a small service, where two or three functions call each other. For a monolithic application with long chains of conditional logic, it is the difference between “it failed” and “it failed where I designed it to fail”.

Replay an error from your logs#

*errors.Error implements slog.LogValuer. When you log it with log/slog, the tag, the message, the route, the metadata and the stack frames are written.

logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Error("create user failed", "err", err)

The keys of the logged object match the fields of errors.ErrorJson, so you can paste a log entry into a test and unmarshal it:

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

    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)
    }
}

The test fails until your code produces the same error on the same route as production did. Now you have the bug in a test, and you can fix it.

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 you hand it off, and the route continues with the caller of Async, 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
    return <-ch
}
// Route: Service.Run->Service.Run.func1->Service.worker.WorkFailed

errors.AsyncRecover does the same, and also turns a panic in the goroutine into an error with the tag errors.TagPanic.

When several goroutines can fail, combine their errors with errors.Join and read them back with errors.All:

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

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

Where to go next#

Two posts of my blog explain the ideas behind the package: Error Handling Challenge is the problem, and Can’t Driven Development is the way of designing software around its errors.