Skip to content

Commit 54641c7

Browse files
author
Baptiste Boussemart
committed
restablish Cause(err)
1 parent 7d83c9b commit 54641c7

File tree

2 files changed

+19
-21
lines changed

2 files changed

+19
-21
lines changed

errors.go

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ func (w *withMessage) Format(s fmt.State, verb rune) {
280280
case 's', 'q':
281281
io.WriteString(s, w.Error())
282282
}
283-
}
283+
}*/
284284

285285
// Cause returns the underlying cause of the error, if possible.
286286
// An error value has a cause if it implements the following
@@ -294,17 +294,14 @@ func (w *withMessage) Format(s fmt.State, verb rune) {
294294
// be returned. If the error is nil, nil will be returned without further
295295
// investigation.
296296
func Cause(err error) error {
297-
type causer interface {
298-
Cause() error
299-
}
300-
301-
for err != nil {
302-
cause, ok := err.(causer)
303-
if !ok {
304-
break
297+
for {
298+
unwrap := goerrors.Unwrap(err)
299+
if unwrap == nil {
300+
if wrap, ok := err.(*withStack); ok {
301+
return wrap.error
302+
}
303+
return err
305304
}
306-
err = cause.Cause()
305+
err = unwrap
307306
}
308-
return err
309307
}
310-
*/

errors_test.go

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
goerrors "errors"
55
"fmt"
66
"io"
7+
"reflect"
78
"testing"
89
)
910

@@ -72,7 +73,7 @@ func TestUnwrap(t *testing.T) {
7273
}
7374
}
7475

75-
/*type nilError struct{}
76+
type nilError struct{}
7677

7778
func (nilError) Error() string { return "nil error" }
7879

@@ -103,14 +104,14 @@ func TestCause(t *testing.T) {
103104
want: io.EOF,
104105
}, {
105106
err: x, // return from errors.New
106-
want: x,
107-
}, {
108-
WithMessage(nil, "whoops"),
109-
nil,
110-
}, {
111-
WithMessage(io.EOF, "whoops"),
112-
io.EOF,
107+
want: x.(*withStack).error,
113108
}, {
109+
// WithMessage(nil, "whoops"),
110+
// nil,
111+
// }, {
112+
// WithMessage(io.EOF, "whoops"),
113+
// io.EOF,
114+
// }, {
114115
WithStack(nil),
115116
nil,
116117
}, {
@@ -124,7 +125,7 @@ func TestCause(t *testing.T) {
124125
t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want)
125126
}
126127
}
127-
}*/
128+
}
128129

129130
func TestWrapfNil(t *testing.T) {
130131
got := Wrapf(nil, "no error")

0 commit comments

Comments
 (0)