-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patherrors_test.go
62 lines (49 loc) · 1.39 KB
/
errors_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package errors_test
import (
"testing"
"github.com/mailgun/errors"
"github.com/mailgun/errors/callstack"
"github.com/stretchr/testify/assert"
)
type ErrTest struct {
Msg string
}
func (e *ErrTest) Error() string {
return e.Msg
}
func (e *ErrTest) Is(target error) bool {
_, ok := target.(*ErrTest)
return ok
}
type ErrHasFields struct {
M string
F map[string]any
}
func (e *ErrHasFields) Error() string {
return e.M
}
func (e *ErrHasFields) Is(target error) bool {
_, ok := target.(*ErrHasFields)
return ok
}
func (e *ErrHasFields) HasFields() map[string]any {
return e.F
}
func TestLast(t *testing.T) {
err := errors.New("bottom")
err = errors.Wrap(err, "last")
err = errors.Wrap(err, "second")
err = errors.Wrap(err, "first")
err = errors.Errorf("wrapped: %w", err)
// errors.As() returns the "first" error in the chain with a stack trace
var first callstack.HasStackTrace
assert.True(t, errors.As(err, &first))
assert.Equal(t, "first: second: last: bottom", first.(error).Error())
// errors.Last() returns the last error in the chain with a stack trace
var last callstack.HasStackTrace
assert.True(t, errors.Last(err, &last))
assert.Equal(t, "last: bottom", last.(error).Error())
// If no stack trace is found, then should not set target and should return false
assert.False(t, errors.Last(errors.New("no stack"), &last))
assert.Equal(t, "last: bottom", last.(error).Error())
}