Guides
Error attributes and typed keys
Preserve structured attributes and the underlying error as it passes through data and API layers.
Define keys and wrap errors
Key specifies an attribute's value type, and Key.Attr constructs a log attribute of that type. The service layer uses Wrap to attach Code, Public, and the user ID. The API layer adds the route. Each layer supplies the context it has.
// 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}"))
}Read attributes across the chain
Key.From looks up a key along the error chain. The inner value wins when the same key occurs more than once. Use From to get the outermost Error, then iterate over its merged attributes with Error.Attrs. Standard-library errors.Is can still match the underlying sentinel error.
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)
}
}