Skip to content

Instantly share code, notes, and snippets.

@komuw
Created November 9, 2019 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komuw/267318096d68384b76d7e3cd560787f3 to your computer and use it in GitHub Desktop.
Save komuw/267318096d68384b76d7e3cd560787f3 to your computer and use it in GitHub Desktop.
Golang errors with stack traces
package main
import (
"fmt"
"runtime"
"strconv"
"strings"
)
/*
API for an errors package that provides stack traces.
*/
type myCustomError struct {
Stack []uintptr
StackTrace string
Err error
}
func (m myCustomError) Error() string {
return m.Err.Error() + m.StackTrace
}
func newMyCustomError(err error) myCustomError {
stack := make([]uintptr, 50)
length := runtime.Callers(2, stack[:])
mStack := stack[:length]
myt := myCustomError{Stack: mStack, StackTrace: getStackTrace(mStack), Err: err}
return myt
}
func getStackTrace(stack []uintptr) string {
trace := ""
frames := runtime.CallersFrames(stack)
for {
frame, more := frames.Next()
if !strings.Contains(frame.File, "runtime/") {
trace = trace + fmt.Sprintf("\n\tFile: %s, Line: %d. Function: %s.", frame.File, frame.Line, frame.Function)
}
if !more {
break
}
}
return trace
}
/*
how to use that API
*/
func error1() (int, error) {
i, err := strconv.Atoi("f42")
if err != nil {
return 0, newMyCustomError(err)
}
return i, nil
}
func main() {
_, err := error1()
if err != nil {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment