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

Go 语言从 1.13 版本开始在标准库
errors
fmt.Errorf
%w
errors
pkg/errors
runtime.Callers
下面介绍如何使用标准库
errors
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'")
}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
如果你不想引入第三方库,也可以通过
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
基本上就这些。错误包装加堆栈,关键在于“包装时记录调用位置”,标准库没做这一步,需要你手动补上。
以上就是怎样使用Golang的errors库包装错误 实现错误堆栈跟踪的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号