Skip to content

Instantly share code, notes, and snippets.

@vardius
Last active May 2, 2022 23:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vardius/56b224de0a69522a24f021642449db17 to your computer and use it in GitHub Desktop.
Save vardius/56b224de0a69522a24f021642449db17 to your computer and use it in GitHub Desktop.
Go errors with stack trace
package main
import (
"bytes"
"errors"
"fmt"
"runtime"
)
type AppError struct {
trace string
err error
}
// Error returns the string representation of the error message.
func (e *AppError) Error() string {
return fmt.Sprintf("%s\n%s", e.trace, e.err)
}
func (e *AppError) Unwrap() error {
return e.err
}
// StackTrace returns the string representation of the error stack trace,
// includeTrace appends caller pcs frames to each error message if possible.
func (e *AppError) StackTrace() (string, error) {
var buf bytes.Buffer
if e.trace != "" {
if _, err := fmt.Fprintf(&buf, "%s", e.trace); err != nil {
return "", err
}
}
if e.err == nil {
return buf.String(), nil
}
var next *AppError
if errors.As(e.err, &next) {
stackTrace, err := next.StackTrace()
if err != nil {
return "", err
}
buf.WriteString(fmt.Sprintf("\n%s", stackTrace))
} else {
return fmt.Sprintf("%s\n%s", buf.String(), e.err), nil
}
return buf.String(), nil
}
func AppenStackTrace(err error) *AppError {
if err == nil {
panic("nil error provided")
}
var buf bytes.Buffer
frame := getFrame(2)
fmt.Fprintf(&buf, "%s", frame.File)
fmt.Fprintf(&buf, ":%d", frame.Line)
fmt.Fprintf(&buf, " %s", frame.Function)
return &AppError{
err: err,
trace: buf.String(),
}
}
func main() {
err := AppenStackTrace(testOne())
fmt.Printf("%s", err)
t, _ := err.StackTrace()
fmt.Printf("\n\n%s", t)
}
func testOne() error {
return fmt.Errorf("testOne: %w", AppenStackTrace(testTwo()))
}
func testTwo() error {
return fmt.Errorf("testTwo: %w", AppenStackTrace(testThree()))
}
func testThree() error {
return AppenStackTrace(fmt.Errorf("internal error"))
}
func getFrame(calldepth int) *runtime.Frame {
pc, file, line, ok := runtime.Caller(calldepth)
if !ok {
return nil
}
frame := &runtime.Frame{
PC: pc,
File: file,
Line: line,
}
funcForPc := runtime.FuncForPC(pc)
if funcForPc != nil {
frame.Func = funcForPc
frame.Function = funcForPc.Name()
frame.Entry = funcForPc.Entry()
}
return frame
}
@vardius
Copy link
Author

vardius commented May 31, 2020

Run this example on The Go Playground

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment