Error wrapping with stack traces for Go
go get github.com/philiprehberger/go-errstackError wrapping with stack traces for Go
go get github.com/philiprehberger/go-errstack
import "github.com/philiprehberger/go-errstack"
file, err := os.Open("config.json")
if err != nil {
return errstack.Wrap(err)
}
user, err := db.FindUser(id)
if err != nil {
return errstack.Wrapf(err, "failed to find user %d", id)
}
if name == "" {
return errstack.New("name must not be empty")
}
if err != nil {
frames := errstack.Stack(err)
for _, f := range frames {
fmt.Println(f) // main.handleRequest (/app/server.go:42)
}
}
Attach key-value metadata to errors without changing the message:
err := errstack.WithValue(err, "request_id", "abc-123")
err = errstack.WithValue(err, "user", "alice")
val, ok := errstack.Value(err, "request_id") // "abc-123", true
Capture a single stack frame at a given depth:
f := errstack.Caller(0) // frame of the current function
fmt.Println(f) // main.handleRequest (/app/server.go:18)
Trim stack frames to focus on relevant packages:
frames := errstack.Stack(err)
frames = errstack.TrimAbove(frames, "myapp/handler") // remove frames above handler
frames = errstack.TrimBelow(frames, "myapp/handler") // remove frames below handler
Get a formatted multi-line stack trace string:
fmt.Println(errstack.StackString(err))
// main.doWork
// /path/to/file.go:42
// main.main
// /path/to/file.go:15
var ErrNotFound = errors.New("not found")
err := errstack.Wrap(ErrNotFound)
errors.Is(err, ErrNotFound) // true
| Function / Type | Description |
|---|---|
Frame | A single stack frame with Function, File, and Line fields |
Frame.String() | Formats the frame as "Function (File:Line)" |
Wrap(err) | Wraps an error with a stack trace; returns nil if err is nil |
Wrapf(err, fmt, args...) | Wraps an error with a formatted message and stack trace |
New(msg) | Creates a new error with a stack trace |
Newf(fmt, args...) | Creates a new formatted error with a stack trace |
Stack(err) | Extracts stack frames from an error; returns nil if none found |
StackString(err) | Returns a formatted multi-line stack trace string |
Caller(skip) | Returns a single stack frame at the given skip depth |
WithValue(err, key, val) | Wraps an error with a key-value annotation |
Value(err, key) | Extracts an annotation value from the error chain |
TrimAbove(frames, pkg) | Removes frames above the first occurrence of pkg |
TrimBelow(frames, pkg) | Removes frames below the last occurrence of pkg |
go test ./...
go vet ./...
If you find this project useful: