go语言从1.13开始通过fmt.errorf的%w动词支持错误包装,可结合errors.is和errors.as进行错误判断,但标准库不记录堆栈信息,需借助github.com/pkg/errors等第三方库或使用runtime.callers手动实现堆栈追踪,推荐开发阶段使用pkg/errors并通过%+v输出堆栈,生产环境可结合日志库记录调用链,最终实现完整的错误上下文和追踪能力。

Go 语言从 1.13 版本开始在标准库
errors中引入了错误包装(error wrapping)机制,允许你将一个错误“包装”进另一个错误中,同时保留原始错误的信息。结合
fmt.Errorf的
%w动词,可以实现错误的链式传递和堆栈追踪。虽然标准库本身不直接提供堆栈信息,但你可以通过组合
errors包和第三方库(如
pkg/errors)或使用
runtime.Callers自行实现堆栈跟踪。
下面介绍如何使用标准库
errors实现错误包装,并结合堆栈信息进行追踪。
1. 使用 fmt.Errorf
和 %w
实现错误包装
当你在一个函数中处理来自底层的错误,又想添加上下文信息时,可以使用
fmt.Errorf配合
%w来包装错误:
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"errors"
"fmt"
)
func readConfig() error {
return errors.New("file not found")
}
func loadConfig() error {
if err := readConfig(); err != nil {
return fmt.Errorf("failed to read config: %w", err)
}
return nil
}
func runApp() error {
if err := loadConfig(); err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
return nil
}
func main() {
if err := runApp(); err != nil {
fmt.Println(err)
}
}输出:
failed to load config: failed to read config: file not found
这展示了错误的链式传播。你可以使用
errors.Is和
errors.As来检查原始错误:
if errors.Is(err, errors.New("file not found")) {
fmt.Println("original error is 'file not found'")
}2. 添加堆栈信息:使用 github.com/pkg/errors
标准库的
errors不记录堆栈。为了实现堆栈追踪,推荐使用流行的第三方库
github.com/pkg/errors(现已归档,但仍广泛使用)或其维护分支如
github.com/ianlopshire/go-errors。
安装:
go get github.com/pkg/errors
示例代码:
package main
import (
"fmt"
"github.com/pkg/errors"
)
func readConfig() error {
return errors.New("file not found")
}
func loadConfig() error {
if err := readConfig(); err != nil {
return errors.Wrap(err, "failed to read config")
}
return nil
}
func runApp() error {
if err := loadConfig(); err != nil {
return errors.Wrap(err, "failed to load config")
}
return nil
}
func main() {
if err := runApp(); err != nil {
fmt.Printf("%+v\n", err) // %+v 显示堆栈
}
}输出会包含完整的调用堆栈:
failed to load config: failed to read config: file not found
stack trace:
- failed to load config
main.loadConfig
/path/to/main.go:14
- failed to read config
main.readConfig
/path/to/main.go:9%+v是关键,它会打印完整的堆栈信息。
3. 使用标准库 + 自定义堆栈(进阶)
如果你不想引入第三方库,也可以通过
runtime手动捕获堆栈:
package main
import (
"fmt"
"runtime"
"strings"
)
type withStack struct {
error
stack []uintptr
}
func (w *withStack) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v", w.Cause())
w.printStack(s)
return
}
fallthrough
case 's':
fmt.Fprintf(s, "%s", w.error)
case 'q':
fmt.Fprintf(s, "%q", w.error)
}
}
func (w *withStack) printStack(s fmt.State) {
for _, pc := range w.stack {
fn := runtime.FuncForPC(pc)
if fn == nil {
continue
}
file, line := fn.FileLine(pc)
fmt.Fprintf(s, "\n %s:%d", trimPath(file), line)
}
}
func (w *withStack) Cause() error { return w.error }
func trimPath(path string) string {
pos := strings.LastIndex(path, "/")
if pos == -1 {
return path
}
return path[pos+1:]
}
func WithStack(err error) error {
if err == nil {
return nil
}
pc := make([]uintptr, 50)
n := runtime.Callers(2, pc)
return &withStack{
error: err,
stack: pc[:n],
}
}使用方式:
func readConfig() error {
return fmt.Errorf("file not found")
}
func loadConfig() error {
if err := readConfig(); err != nil {
return WithStack(fmt.Errorf("failed to read config: %w", err))
}
return nil
}
func main() {
if err := loadConfig(); err != nil {
fmt.Printf("%+v\n", err)
}
}输出类似:
failed to read config: file not found main.loadConfig:20 main.main:30
总结关键点
-
标准库
errors
+%w
:适合错误包装和链式判断(Is
/As
),但无堆栈。 -
github.com/pkg/errors
:提供Wrap
和%+v
,开箱即用的堆栈追踪,适合开发阶段。 - 自定义堆栈:更轻量,避免依赖,但需自己维护。
-
生产建议:开发阶段用
pkg/errors
,上线后可通过日志记录堆栈,或结合 zap、logrus 等日志库输出。
基本上就这些。错误包装加堆栈,关键在于“包装时记录调用位置”,标准库没做这一步,需要你手动补上。










