使用指南
错误属性与类型化键
在错误穿过数据层与 API 层时保留结构化属性和原始错误。
定义键与包装错误
Key 带有属性值的类型,Key.Attr 创建同一类型的日志属性。业务层用 Wrap 写入 Code、Public 和用户编号,API 层再附加路由。每层只记录自己知道的上下文。
// 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}"))
}按链读取属性
Key.From 在错误链上寻找键,遇到同名键时以内层为准。调用 From 可取得链上的最外层 Error,再通过 Error.Attrs 遍历合并的属性。标准库 errors.Is 仍可匹配底层的哨兵错误。
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)
}
}