luminyra

Quickstart

Add an error code and user ID to a chain and retrieve both from the outer error.

Run the wrapping example

Use Go 1.27 or later. Install errs, save the complete example as main.go, and run go run .. From the errs source directory, run go run ./examples/basic.

go get github.com/luminyra/errs
Complete error chain example
// Command basic attaches slog attributes to errors across layers with errs and
// reads them back with typed keys.
package main

import (
	"errors"
	"fmt"
	"log/slog"

	"github.com/luminyra/errs"
)

// ErrNotFound is the sentinel error of the data layer.
var ErrNotFound = errors.New("not found")

// UserID is a typed attribute key: it accepts only an int and reads back an
// int.
const UserID errs.Key[int] = "user_id"


// The domain layer attaches an error code, the user ID and a message that is
// safe to show to users.
func findUser(id int) error {
	return errs.Wrap(ErrNotFound, "find user",
		errs.Code.Attr("USER_NOT_FOUND"),
		errs.Public.Attr("We could not find that user."),
		UserID.Attr(id),
	)
}

// The API layer wraps the error again and adds the route. Any slog.Attr can be
// attached.
func handleGetUser(id int) error {
	return errs.Wrap(findUser(id), "get user", slog.String("route", "GET /users/{id}"))
}


func main() {
	err := handleGetUser(42)

	fmt.Println(err)                         // the whole message chain
	fmt.Println(errors.Is(err, ErrNotFound)) // the sentinel still matches

	code, _ := errs.Code.From(err) // the innermost value in the chain
	public, _ := errs.Public.From(err)
	id, _ := UserID.From(err) // an int, no type assertion
	fmt.Println("code:  ", code)
	fmt.Println("public:", public)
	fmt.Println("userID:", id)

	if e, ok := errs.From(err); ok {
		for _, a := range e.Attrs() { // attributes merged across the chain
			fmt.Println("attr:  ", a)
		}
	}
}
View on GitHub

Check matching and attribute lookup

The two calls to Wrap record context for the lookup and for handling the user's request. The true in the output shows that errors.Is still matches the underlying error. Key.From reads the user ID directly as an integer, and Code reads the application error code.

errs/example_test.go
err := errs.Wrap(fs.ErrNotExist, "find user", errs.Code.Attr("USER_NOT_FOUND"), UserID.Attr(42))
err = errs.Wrap(err, "get profile", slog.String("route", "/users/{id}"))

code, _ := errs.Code.From(err)
id, _ := UserID.From(err)
fmt.Println(err)
fmt.Println(errors.Is(err, fs.ErrNotExist), code, id)
Expected output
get profile: find user: file does not exist
true USER_NOT_FOUND 42
View on GitHub

Read how to merge attributes across the chain.

On this page