Compare commits

...

2 commits

Author SHA1 Message Date
5cc2a3dcbb improve annotations
All checks were successful
continuous-integration/drone/push Build is passing
2021-10-16 20:37:14 +02:00
8422e93f02 Add extended TryErr 2021-10-16 19:55:31 +02:00
4 changed files with 196 additions and 84 deletions

View file

@ -2,7 +2,6 @@ package main
import ( import (
"bufio" "bufio"
"errors"
"flag" "flag"
"fmt" "fmt"
"io" "io"
@ -26,8 +25,8 @@ type line struct {
Types []string Types []string
} }
func parseDefinitions(defFileName string, outFileName string) (err error) { func parseDefinitions(defFileName string, outFileName string) (err try.TryErr) {
defer try.Annotate("error parsing definitions", &err) defer try.Annotate(&err, "error parsing definitions")
defFile := try.File(os.Open(defFileName)) defFile := try.File(os.Open(defFileName))
@ -78,12 +77,12 @@ func parseDefinitions(defFileName string, outFileName string) (err error) {
return return
} }
func parseLine(lineStr string, imports map[string]bool) (*line, error) { func parseLine(lineStr string, imports map[string]bool) (*line, try.TryErr) {
lineParts := strings.Split(lineStr, ";") lineParts := strings.Split(lineStr, ";")
lineData := line{} lineData := line{}
if len(lineParts) < 2 { if len(lineParts) < 2 {
return nil, errors.New("missing type name") return nil, try.NewErr("missing type name")
} }
// Parse variable name // Parse variable name
@ -92,7 +91,7 @@ func parseLine(lineStr string, imports map[string]bool) (*line, error) {
lineData.Name = match[1] lineData.Name = match[1]
lineData.WithSlice = match[2] != "" lineData.WithSlice = match[2] != ""
} else { } else {
return nil, errors.New("invalid variable name") return nil, try.NewErr("invalid variable name")
} }
// Parse type name(s) // Parse type name(s)
@ -103,7 +102,7 @@ func parseLine(lineStr string, imports map[string]bool) (*line, error) {
} }
} }
if len(lineData.Types) == 0 { if len(lineData.Types) == 0 {
return nil, errors.New("invalid type name") return nil, try.NewErr("invalid type name")
} }
// Parse imports // Parse imports
@ -115,7 +114,7 @@ func parseLine(lineStr string, imports map[string]bool) (*line, error) {
return &lineData, nil return &lineData, nil
} }
func copyLibrary(targetDir string, noTests, noStds bool) (caught error) { func copyLibrary(targetDir string, noTests, noStds bool) (caught try.TryErr) {
defer try.Return(&caught) defer try.Return(&caught)
filesToCopy := []string{"try.go"} filesToCopy := []string{"try.go"}
@ -144,14 +143,6 @@ func copyLibrary(targetDir string, noTests, noStds bool) (caught error) {
try.Check(dest.Close()) try.Check(dest.Close())
} }
// Add go-generate command
gencmd := "\n//go:generate go run code.thetadev.de/ThetaDev/gotry/gotry_generate " +
"-def types.csv -o .\n"
f := try.File(
os.OpenFile(filepath.Join(targetDir, "try.go"), os.O_APPEND|os.O_WRONLY, 0o644))
try.Empty(f.WriteString(gencmd))
try.Check(f.Close())
// If not present, add definition file template // If not present, add definition file template
definitionFile := filepath.Join(targetDir, "types.csv") definitionFile := filepath.Join(targetDir, "types.csv")
@ -170,7 +161,7 @@ func goFmt(goFile string) error {
} }
func main() { func main() {
defer try.Catch(func(err error) { defer try.Catch(func(err try.TryErr) {
fmt.Println("Error: " + err.Error()) fmt.Println("Error: " + err.Error())
}) })

View file

@ -15,7 +15,7 @@ func TestStrHelper_noThrow(t *testing.T) {
} }
func TestStrHelper_throw(t *testing.T) { func TestStrHelper_throw(t *testing.T) {
var err error var err TryErr
defer Return(&err) defer Return(&err)
String(throw()) String(throw())
@ -31,8 +31,8 @@ func TestStrStrHelper(t *testing.T) {
} }
func Example_copyFile() { func Example_copyFile() {
copyFile := func(src, dst string) (err error) { copyFile := func(src, dst string) (err TryErr) {
defer Returnf(&err, "copy %s %s", src, dst) defer Annotate(&err, fmt.Sprintf("copy %s %s", src, dst))
// These helpers are as fast as Check() calls // These helpers are as fast as Check() calls
r := File(os.Open(src)) r := File(os.Open(src))

View file

@ -9,9 +9,118 @@ https://github.com/lainio/err2
import ( import (
"errors" "errors"
"fmt" "fmt"
"regexp"
"runtime"
"runtime/debug" "runtime/debug"
"strings"
) )
// TryErr is an interface for an error with extended stack info.
type TryErr interface {
Error() string
Unwrap() error
CallStack() []call
CallStackString() string
PrintCallStack()
GetData() *tryErrData
Annotate(msg string)
}
// tryErrObj is an extended error struct.
type tryErrObj struct {
err error
annotations []string
callStack []call
}
// tryErrData is exported error data. Can be converted to JSON.
type tryErrData struct {
Msg string `json:"msg"`
Annotations []string `json:"annotations"`
CallStack []call `json:"call_stack"`
}
type call struct {
Function string `json:"fn"`
Line int `json:"l"`
}
func newErr(err error) *tryErrObj {
terr := &tryErrObj{err: err, callStack: []call{}}
pc, _, _, ok := runtime.Caller(0)
if !ok {
return terr
}
thisFnc := runtime.FuncForPC(pc)
if thisFnc == nil {
return terr
}
rexp := regexp.MustCompile(`.+\/`)
thisPkg := rexp.FindString(thisFnc.Name())
for i := 1; ; i++ {
pc, f, l, ok := runtime.Caller(i)
if !ok {
break
}
fnc := runtime.FuncForPC(pc).Name()
if strings.HasPrefix(fnc, thisPkg) && !strings.HasSuffix(f, "_test.go") {
continue
}
terr.callStack = append(terr.callStack, call{Line: l, Function: fnc})
}
return terr
}
func NewErr(msg string) *tryErrObj {
return newErr(errors.New(msg))
}
func (e *tryErrObj) Error() string {
msgs := e.annotations
msgs = append(msgs, e.err.Error())
return strings.Join(msgs, ": ")
}
func (e *tryErrObj) Unwrap() error {
return e.err
}
func (e *tryErrObj) CallStack() []call {
return e.callStack
}
func (e *tryErrObj) CallStackString() string {
res := fmt.Sprintf("ERROR: %s\n", e.err.Error())
for _, c := range e.callStack {
res += fmt.Sprintf("%s:%d\n", c.Function, c.Line)
}
return res
}
func (e *tryErrObj) PrintCallStack() {
fmt.Println(e.CallStackString())
}
func (e *tryErrObj) GetData() *tryErrData {
return &tryErrData{
Msg: e.err.Error(),
CallStack: e.callStack,
Annotations: e.annotations,
}
}
func (e *tryErrObj) Annotate(msg string) {
e.annotations = append(e.annotations, msg)
}
// Empty is a helper method to handle errors of func() (string, error) functions. // Empty is a helper method to handle errors of func() (string, error) functions.
func Empty(_ interface{}, err error) { func Empty(_ interface{}, err error) {
Check(err) Check(err)
@ -30,7 +139,7 @@ func Any(args ...interface{}) []interface{} {
// {return err} on happy path. // {return err} on happy path.
func Check(err error) { func Check(err error) {
if err != nil { if err != nil {
panic(err) panic(newErr(err))
} }
} }
@ -45,7 +154,7 @@ func check(args []interface{}) {
if !ok { if !ok {
panic("wrong signature") panic("wrong signature")
} }
panic(err) panic(newErr(err))
} }
} }
@ -53,7 +162,7 @@ func check(args []interface{}) {
// functions returning errors them self. For those functions that doesn't // functions returning errors them self. For those functions that doesn't
// return errors there is a Catch function. Note! The handler function f is // return errors there is a Catch function. Note! The handler function f is
// called only when err != nil. // called only when err != nil.
func Handle(err *error, f func()) { func Handle(err *TryErr, f func()) {
// This and Catch are similar but we need to call recover() here because // This and Catch are similar but we need to call recover() here because
// how it works with defer. We cannot refactor these to use same function. // how it works with defer. We cannot refactor these to use same function.
@ -69,42 +178,25 @@ func Handle(err *error, f func()) {
if *err != nil { if *err != nil {
f() f()
} }
case error: case TryErr:
// We or someone did transport this error thru panic. // We or someone did transport this error thru panic.
*err = r.(error) *err = r.(TryErr)
f() f()
default: default:
panic(r) panic(r)
} }
} }
// Returnf wraps an error. It's similar to fmt.Errorf, but it's called only if
// error != nil.
func Returnf(err *error, format string, args ...interface{}) {
// This and Handle are similar but we need to call recover here because how
// it works with defer. We cannot refactor these two to use same function.
if r := recover(); r != nil {
e, ok := r.(error)
if !ok {
panic(r) // Not ours, carry on panicking
}
*err = fmt.Errorf(format+": %v", append(args, e)...)
} else if *err != nil { // if other handlers call recovery() we still..
*err = fmt.Errorf(format+": %v", append(args, *err)...)
}
}
// Catch is a convenient helper to those functions that doesn't return errors. // Catch is a convenient helper to those functions that doesn't return errors.
// Go's main function is a good example. Note! There can be only one deferred // Go's main function is a good example. Note! There can be only one deferred
// Catch function per non error returning function. See Handle for more // Catch function per non error returning function. See Handle for more
// information. // information.
func Catch(f func(err error)) { func Catch(f func(err TryErr)) {
// This and Handle are similar but we need to call recover here because how // This and Handle are similar but we need to call recover here because how
// it works with defer. We cannot refactor these 2 to use same function. // it works with defer. We cannot refactor these 2 to use same function.
if r := recover(); r != nil { if r := recover(); r != nil {
e, ok := r.(error) e, ok := r.(TryErr)
if !ok { if !ok {
panic(r) panic(r)
} }
@ -114,12 +206,12 @@ func Catch(f func(err error)) {
// CatchAll is a helper function to catch and write handlers for all errors and // CatchAll is a helper function to catch and write handlers for all errors and
// all panics thrown in the current go routine. // all panics thrown in the current go routine.
func CatchAll(errorHandler func(err error), panicHandler func(v interface{})) { func CatchAll(errorHandler func(err TryErr), panicHandler func(v interface{})) {
// This and Handle are similar but we need to call recover here because how // This and Handle are similar but we need to call recover here because how
// it works with defer. We cannot refactor these 2 to use same function. // it works with defer. We cannot refactor these 2 to use same function.
if r := recover(); r != nil { if r := recover(); r != nil {
e, ok := r.(error) e, ok := r.(TryErr)
if ok { if ok {
errorHandler(e) errorHandler(e)
} else { } else {
@ -131,12 +223,12 @@ func CatchAll(errorHandler func(err error), panicHandler func(v interface{})) {
// CatchTrace is a helper function to catch and handle all errors. It recovers a // CatchTrace is a helper function to catch and handle all errors. It recovers a
// panic as well and prints its call stack. This is preferred helper for go // panic as well and prints its call stack. This is preferred helper for go
// workers on long running servers. // workers on long running servers.
func CatchTrace(errorHandler func(err error)) { func CatchTrace(errorHandler func(err TryErr)) {
// This and Handle are similar but we need to call recover here because how // This and Handle are similar but we need to call recover here because how
// it works with defer. We cannot refactor these 2 to use same function. // it works with defer. We cannot refactor these 2 to use same function.
if r := recover(); r != nil { if r := recover(); r != nil {
e, ok := r.(error) e, ok := r.(TryErr)
if ok { if ok {
errorHandler(e) errorHandler(e)
} else { } else {
@ -149,12 +241,12 @@ func CatchTrace(errorHandler func(err error)) {
// Return is same as Handle but it's for functions which don't wrap or annotate // Return is same as Handle but it's for functions which don't wrap or annotate
// their errors. If you want to annotate errors see Annotate for more // their errors. If you want to annotate errors see Annotate for more
// information. // information.
func Return(err *error) { func Return(err *TryErr) {
// This and Handle are similar but we need to call recover here because how // This and Handle are similar but we need to call recover here because how
// it works with defer. We cannot refactor these two to use same function. // it works with defer. We cannot refactor these two to use same function.
if r := recover(); r != nil { if r := recover(); r != nil {
e, ok := r.(error) e, ok := r.(TryErr)
if !ok { if !ok {
panic(r) // Not ours, carry on panicking panic(r) // Not ours, carry on panicking
} }
@ -165,20 +257,18 @@ func Return(err *error) {
// Annotate is for annotating an error. It's similar to Returnf but it takes only // Annotate is for annotating an error. It's similar to Returnf but it takes only
// two arguments: a prefix string and a pointer to error. It adds ": " between // two arguments: a prefix string and a pointer to error. It adds ": " between
// the prefix and the error text automatically. // the prefix and the error text automatically.
func Annotate(prefix string, err *error) { func Annotate(err *TryErr, msg string) {
// This and Handle are similar but we need to call recover here because how // This and Handle are similar but we need to call recover here because how
// it works with defer. We cannot refactor these two to use same function. // it works with defer. We cannot refactor these two to use same function.
if r := recover(); r != nil { if r := recover(); r != nil {
e, ok := r.(error) e, ok := r.(TryErr)
if !ok { if !ok {
panic(r) // Not ours, carry on panicking panic(r) // Not ours, carry on panicking
} }
*err = e *err = e
format := prefix + ": " + e.Error() e.Annotate(msg)
*err = errors.New(format)
} else if *err != nil { // if other handlers call recovery() we still.. } else if *err != nil { // if other handlers call recovery() we still..
format := prefix + ": " + (*err).Error() (*err).Annotate(msg)
*err = errors.New(format)
} }
} }

View file

@ -8,6 +8,7 @@ https://github.com/lainio/err2
import ( import (
"fmt" "fmt"
"strings"
"testing" "testing"
) )
@ -64,7 +65,7 @@ func TestAny_noError(t *testing.T) {
} }
func TestDefault_Error(t *testing.T) { func TestDefault_Error(t *testing.T) {
var err error var err TryErr
defer Return(&err) defer Return(&err)
Any(throw()) Any(throw())
@ -73,7 +74,7 @@ func TestDefault_Error(t *testing.T) {
} }
func TestAny_Error(t *testing.T) { func TestAny_Error(t *testing.T) {
var err error var err TryErr
defer Handle(&err, func() {}) defer Handle(&err, func() {})
Any(throw()) Any(throw())
@ -82,7 +83,7 @@ func TestAny_Error(t *testing.T) {
} }
func panickingHandle() { func panickingHandle() {
var err error var err TryErr
defer Handle(&err, func() {}) defer Handle(&err, func() {})
Any(wrongSignature()) Any(wrongSignature())
@ -98,7 +99,7 @@ func TestPanickingCarryOn_Handle(t *testing.T) {
} }
func panickingCatchAll() { func panickingCatchAll() {
defer CatchAll(func(err error) {}, func(v interface{}) {}) defer CatchAll(func(err TryErr) {}, func(v interface{}) {})
Any(wrongSignature()) Any(wrongSignature())
} }
@ -113,7 +114,7 @@ func TestPanickingCatchAll(t *testing.T) {
} }
func panickingCatchTrace() { func panickingCatchTrace() {
defer CatchTrace(func(err error) {}) defer CatchTrace(func(err TryErr) {})
Any(wrongSignature()) Any(wrongSignature())
} }
@ -128,7 +129,7 @@ func TestPanickingCatchTrace(t *testing.T) {
} }
func panickingReturn() { func panickingReturn() {
var err error var err TryErr
defer Return(&err) defer Return(&err)
Any(wrongSignature()) Any(wrongSignature())
@ -144,7 +145,7 @@ func TestPanicking_Return(t *testing.T) {
} }
func panickingCatch() { func panickingCatch() {
defer Catch(func(err error) {}) defer Catch(func(err TryErr) {})
Any(wrongSignature()) Any(wrongSignature())
} }
@ -159,7 +160,7 @@ func TestPanicking_Catch(t *testing.T) {
} }
func TestCatch_Error(t *testing.T) { func TestCatch_Error(t *testing.T) {
defer Catch(func(err error) { defer Catch(func(err TryErr) {
// fmt.Printf("error and defer handling:%s\n", err) // fmt.Printf("error and defer handling:%s\n", err)
}) })
@ -169,15 +170,15 @@ func TestCatch_Error(t *testing.T) {
} }
func ExampleReturn() { func ExampleReturn() {
var err error var err TryErr
defer Return(&err) defer Return(&err)
Any(noThrow()) Any(noThrow())
// Output: // Output:
} }
func ExampleAnnotate() { func ExampleAnnotate() {
annotated := func() (err error) { annotated := func() (err TryErr) {
defer Annotate("annotated", &err) defer Annotate(&err, "annotated")
Any(throw()) Any(throw())
return err return err
} }
@ -186,33 +187,22 @@ func ExampleAnnotate() {
// Output: annotated: this is an ERROR // Output: annotated: this is an ERROR
} }
func ExampleReturnf() {
annotated := func() (err error) {
defer Returnf(&err, "annotated: %s", "err2")
Any(throw())
return err
}
err := annotated()
fmt.Printf("%v", err)
// Output: annotated: err2: this is an ERROR
}
func ExampleAnnotate_deferStack() { func ExampleAnnotate_deferStack() {
annotated := func() (err error) { annotated := func() (err TryErr) {
defer Annotate("annotated 2nd", &err) defer Annotate(&err, "annotated 2nd")
defer Annotate("annotated 1st", &err) defer Annotate(&err, "annotated 1st")
Any(throw()) Any(throw())
return err return err
} }
err := annotated() err := annotated()
fmt.Printf("%v", err) fmt.Printf("%v", err)
// Output: annotated 2nd: annotated 1st: this is an ERROR // Output: annotated 1st: annotated 2nd: this is an ERROR
} }
func ExampleHandle() { func ExampleHandle() {
doSomething := func(a, b int) (err error) { doSomething := func(a, b int) (err TryErr) {
defer Handle(&err, func() { defer Handle(&err, func() {
err = fmt.Errorf("error with (%d, %d): %w", a, b, err) err.Annotate(fmt.Sprintf("error with (%d, %d)", a, b))
}) })
Any(throw()) Any(throw())
return err return err
@ -278,3 +268,44 @@ func BenchmarkRecursionWithErrorCheck_NotRelated(b *testing.B) {
} }
} }
} }
func TestNewTryErr(t *testing.T) {
tryErr := NewErr("I f*cked up")
callStack := tryErr.CallStackString()
if !strings.HasPrefix(callStack, "ERROR: I f*cked up\n") {
fmt.Println("Call stack does not have prefix.\n" + callStack)
t.Fail()
}
if strings.Count(callStack, "\n") != 4 {
fmt.Println("Call stack is not 4 lines long.\n" + callStack)
t.Fail()
}
}
func TestGetData(t *testing.T) {
tryErr := NewErr("I f*cked up")
tryErr.Annotate("test1")
tryErr.Annotate("test2")
data := tryErr.GetData()
if data.Msg != "I f*cked up" {
fmt.Println("wrong msg")
t.Fail()
}
if data.Annotations[0] != "test1" {
fmt.Println("wrong annotation#0")
t.Fail()
}
if data.Annotations[1] != "test2" {
fmt.Println("wrong annotation#1")
t.Fail()
}
if len(data.CallStack) != 3 {
fmt.Println("call stack length != 3, " + fmt.Sprint(len(data.CallStack)))
t.Fail()
}
}