Skip to content
This repository was archived by the owner on Mar 15, 2024. It is now read-only.

Commit 113abc6

Browse files
committed
better catch multilevel errors
1 parent 9fe06c4 commit 113abc6

File tree

2 files changed

+41
-6
lines changed

2 files changed

+41
-6
lines changed

helium.go

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -128,22 +128,25 @@ func CatchTrace(err error) {
128128
// digging into the root of the problem
129129
for {
130130
var (
131+
ok bool
131132
v = reflect.ValueOf(err)
132133
fn reflect.Value
133134
)
134135

135136
if v.Type().Kind() != reflect.Struct {
136137
break
137-
}
138-
139-
if !v.FieldByName("Reason").IsValid() || !v.FieldByName("Func").IsValid() {
138+
} else if !v.FieldByName("Reason").IsValid() {
140139
break
140+
} else if v.FieldByName("Func").IsValid() {
141+
fn = v.FieldByName("Func")
141142
}
142143

143-
fn = v.FieldByName("Func")
144-
err = v.FieldByName("Reason").Interface().(error)
145-
146144
fmt.Printf("Place: %#v\nReason: %s\n\n", fn, err)
145+
146+
if err, ok = v.FieldByName("Reason").Interface().(error); !ok {
147+
err = v.Interface().(error)
148+
break
149+
}
147150
}
148151

149152
panic(err)

helium_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"io/ioutil"
99
"log"
1010
"os"
11+
"strconv"
1112
"testing"
1213

1314
"bou.ke/monkey"
@@ -25,6 +26,12 @@ type (
2526
heliumErrApp struct{}
2627

2728
Error string
29+
30+
TestError struct {
31+
Index int
32+
Func interface{}
33+
Reason error
34+
}
2835
)
2936

3037
const ErrTest = Error("test")
@@ -33,6 +40,10 @@ func (e Error) Error() string {
3340
return string(e)
3441
}
3542

43+
func (e TestError) Error() string {
44+
return "error level: " + strconv.Itoa(e.Index)
45+
}
46+
3647
func (h heliumApp) Run(ctx context.Context) error { return nil }
3748
func (h heliumErrApp) Run(ctx context.Context) error { return ErrTest }
3849

@@ -253,5 +264,26 @@ func TestHelium(t *testing.T) {
253264

254265
require.Empty(t, exitCode)
255266
})
267+
268+
t.Run("should catch multi level errors", func(t *testing.T) {
269+
var exitCode int
270+
271+
monkey.Patch(os.Exit, func(code int) { exitCode = code; panic(code) })
272+
monkey.Patch(log.Fatal, func(...interface{}) { exitCode = 2; panic(exitCode) })
273+
274+
require.Panics(t, func() {
275+
CatchTrace(TestError{
276+
Index: 1,
277+
Reason: TestError{
278+
Index: 2,
279+
Reason: TestError{
280+
Index: 3,
281+
},
282+
},
283+
})
284+
})
285+
286+
require.Empty(t, exitCode)
287+
})
256288
})
257289
}

0 commit comments

Comments
 (0)