Note: This is the documentation for v2 of the
stacktrace
module.
For v1 documentation, see README.v1.md.
Package stacktrace provides utilities for capturing and inspecting stack traces associated with errors.
- Wraps errors with a single stack trace
- Typically, a single error chain contains at most one stack trace
- Extracts the stack trace from an error
The most basic way to create an error with a stack trace is to use the Trace function:
err := stacktrace.Trace(os.Chdir(target))
There are Trace2, Trace3, and Trace4: These are overloads of Trace that return the given values unchanged if err is nil. If err is not nil, it wraps err with stack trace information before returning.
file, err := stacktrace.Trace2(os.Open(file))
For convenience, you can use New and Errorf as drop-in replacements for errors.New and fmt.Errorf:
err := stacktrace.New("some error")
err := stacktrace.Errorf("some error: %w", originalErr)
To get a formatted string representation of stack trace information from an error:
// Get as a string.
// This is equivalent to calling `err.Error()`
// if `err` does not contain stack trace information.
// `s` is an empty string if `err` is nil.
s := stacktrace.Format(err)
Use Format.
For example, the s
contains multiline string like below:
chdir /no/such/dir: no such file or directory (run.go:10 main.run)
example.com/hello/run.go:10 main.run
example.com/hello/main.go:11 main.main
To extract stack trace information from an error:
// Get as a DebugInfo instance
info := stacktrace.GetDebugInfo(err)
The DebugInfo type is compatible with google.golang.org/genproto/googleapis/rpc/errdetails.DebugInfo.
For example, the info contains information like below:
{
"detail": "chdir /no/such/dir: no such file or directory (run.go:10 main.run)",
"stack_entries": [
"example.com/hello/run.go:10 main.run",
"example.com/hello/main.go:11 main.main"
]
}
Alternatively, you can use ListStackTracers to extract the StackTracer instances from an error chain. CallersFrames is available in Go 1.23 or later.
list := stacktrace.ListStackTracers(err)
for _, v := range list {
for frame := range stacktrace.CallersFrames(v.StackTrace()) {
_, _ = frame.File, frame.Line
}
}
Adding stack traces to errors involves some overhead. In performance-critical sections, consider using traditional error handling and adding stack traces at higher levels of your application.