Created
November 9, 2019 15:36
-
-
Save komuw/267318096d68384b76d7e3cd560787f3 to your computer and use it in GitHub Desktop.
Golang errors with stack traces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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