Linesep, Stacktraces tools

This commit is contained in:
Jürgen Edelbluth 2023-10-06 20:11:27 +02:00
parent ab6f5a92f0
commit a3f6c03851
Signed by: jed
GPG Key ID: 6DEAEDD5CDB646DF
2 changed files with 85 additions and 0 deletions

10
pkg/osdep/linesep.go Normal file
View File

@ -0,0 +1,10 @@
package osdep
import "os"
func GetLineSep() string {
if os.PathSeparator == '\\' {
return "\r\n"
}
return "\n"
}

75
pkg/stacktrace/main.go Normal file
View File

@ -0,0 +1,75 @@
package stacktrace
import (
"fmt"
"git.codebau.dev/goblins/commons/pkg/osdep"
"runtime"
)
type ErrorReporter struct {
EnableStacktraces bool
}
type StackElement struct {
File string
FunctionName string
Line int
}
type ErrorWithStacktrace struct {
error
Stack *[]*StackElement
}
func (s *ErrorWithStacktrace) build(enableStackTraces bool) {
if !enableStackTraces || s == nil || s.error == nil {
return
}
readingCallers := true
callerIncrement := 1
var stack []*StackElement
for readingCallers {
callerIncrement += 1
caller, file, line, ok := runtime.Caller(callerIncrement)
if !ok {
readingCallers = false
} else {
funcName := ""
if function := runtime.FuncForPC(caller); function != nil {
funcName = function.Name()
}
stack = append(stack, &StackElement{
File: file,
FunctionName: funcName,
Line: line,
})
s.Stack = &stack
}
}
}
func (s *ErrorWithStacktrace) Format() string {
if s == nil || s.Stack == nil || len(*s.Stack) == 0 {
return "[no stack trace]"
}
out := ""
lineSep := osdep.GetLineSep()
for i, se := range *s.Stack {
out += fmt.Sprintf("%7d | %s:%d%s %s%s", i, se.File, se.Line, lineSep, se.FunctionName, lineSep)
}
return out
}
func (s *ErrorWithStacktrace) Stacktrace() *[]*StackElement {
return s.Stack
}
func (r *ErrorReporter) New(err error) *ErrorWithStacktrace {
s := &ErrorWithStacktrace{error: err}
s.build(r.EnableStacktraces)
return s
}
func New(enableStacktraces bool) *ErrorReporter {
return &ErrorReporter{EnableStacktraces: enableStacktraces}
}