Skip to content

Commit 07b2b57

Browse files
committed
Add WithCause
1 parent d2028f1 commit 07b2b57

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

error.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,16 @@ func WithStack(err error) error {
4343
return err
4444
}
4545
}
46+
47+
// WithCause adds a cause to the provided error if it is an Err or *Err.
48+
func WithCause(err error, cause error) error {
49+
if e, ok := err.(Err); ok {
50+
e.Cause = cause
51+
return e
52+
} else if e, ok := err.(*Err); ok {
53+
e.Cause = cause
54+
return e
55+
} else {
56+
return err
57+
}
58+
}

errors_test.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ func NewCustomError(message string) error {
9696
}
9797

9898
func TestWithStack(t *testing.T) {
99-
t.Run("when WithStack is called on a custom error type composed with Err, it should add a stack trace", func(t *testing.T) {
99+
t.Run("when WithStack is provided with an error of type Err, it should add a stack trace to the error", func(t *testing.T) {
100100
err := NewCustomError("this is a custom error type with stack")
101101

102102
if err.(CustomError).Stack == nil {
@@ -115,3 +115,26 @@ func TestWithStack(t *testing.T) {
115115
}
116116
})
117117
}
118+
119+
// CustomError2 is a custom error type composed with Err.
120+
type CustomError2 struct {
121+
*Err
122+
}
123+
124+
// NewCustom2Error returns a new CustomError2 and adds a cause to the error.
125+
func NewCustom2Error(message string, cause error) error {
126+
customError2 := CustomError2{Err: &Err{Message: message}}
127+
WithCause(customError2.Err, cause)
128+
return customError2
129+
}
130+
131+
func TestWithCause(t *testing.T) {
132+
t.Run("when WithCause is provided with an error and a cause, it should add the cause to the error", func(t *testing.T) {
133+
causeErr := New("inner error")
134+
err := NewCustom2Error("outer error", causeErr)
135+
136+
if err.(CustomError2).Cause != causeErr {
137+
t.Errorf(`expected cause to be %v, got %v`, causeErr, err.(CustomError2).Cause)
138+
}
139+
})
140+
}

0 commit comments

Comments
 (0)