luminyra

快速上手

在错误链中添加错误码和用户编号,再从外层错误读取属性。

运行跨层包装示例

使用 Go 1.27 或更高版本,安装 errs 后把完整示例保存为 main.go 并运行 go run .。在 errs 源码目录可直接运行 go run ./examples/basic。

go get github.com/luminyra/errs
完整错误链示例
// 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)
		}
	}
}
在 GitHub 查看

检查匹配与读取

两次 Wrap 分别记录查找和处理用户请求时的上下文。输出中的 true 表示标准库 errors.Is 仍匹配底层错误。用 Key.From 能把用户编号直接读成整数,用 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)
预期输出
get profile: find user: file does not exist
true USER_NOT_FOUND 42
在 GitHub 查看

继续阅读 错误属性如何沿链合并。

本页目录