Skip to content

Commit be404a6

Browse files
committed
Refactor Error.Unwrap to return []error
1 parent b96f02b commit be404a6

5 files changed

Lines changed: 71 additions & 34 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
77

88

99
## [Unreleased](https://github.com/gravitton/errors/compare/v1.3.0...master)
10+
### Changed
11+
- `Error.Unwrap` returns `[]error` holding both the wrapped error and the cause, so `errors.Unwrap` now returns nil for an `*Error` (**breaking**)
12+
13+
### Fixed
14+
- `Error.WithCause` no longer hides the wrapped error from `errors.Is` and `errors.As`
15+
- `Error.Is` no longer panics when a field holds a comparable type with an uncomparable dynamic value, such as a struct with an `any` field containing a slice
1016

1117

1218
## v1.3.0 (2026-08-26)(https://github.com/gravitton/errors/compare/v1.2.1...v1.3.0)

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ go get github.com/gravitton/errors
2121

2222
This package is a drop-in replacement for the standard library `errors` package. It re-exports `Unwrap`, `Is`, `As`, and `AsType` unchanged, so you can swap the import and gain `Error` and `MultiError` without changing any existing call sites.
2323

24-
`New` returns an `*Error` instead of an `error`, and `Join` returns a `*MultiError`.
24+
`New` returns an `*Error` instead of an `error`. `Error` and `MultiError` both implement `Unwrap() []error`, so `errors.Unwrap` returns nil for them; use `Is` and `As` to inspect the chain.
2525

2626
```diff
2727
- "errors"

‎error.go‎

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,9 @@ func (e *Error) Error() string {
6969
return e.err.Error()
7070
}
7171

72-
// Fields returns a copy of the structured key-value data attached to this error.
73-
// Mutating the result does not affect the error.
72+
// Fields returns a shallow copy of the structured key-value data attached to
73+
// this error. Adding or removing keys does not affect the error; values that
74+
// are maps, slices or pointers remain shared.
7475
func (e *Error) Fields() map[string]any {
7576
if e == nil {
7677
return nil
@@ -119,27 +120,31 @@ func (e *Error) WithCause(err error) *Error {
119120
}
120121
}
121122

122-
// Unwrap returns the cause if one was set via WithCause; otherwise it returns
123-
// the underlying error created by New, Newf, or Wrap.
124-
func (e *Error) Unwrap() error {
123+
// Unwrap returns the underlying error created by New, Newf or Wrap, followed
124+
// by the cause if one was set via WithCause. Both stay visible to errors.Is
125+
// and errors.As, so attaching a cause never hides the wrapped error.
126+
// A nil *Error returns nil.
127+
func (e *Error) Unwrap() []error {
125128
if e == nil {
126129
return nil
127130
}
128131

132+
errs := []error{e.err}
129133
if e.cause != nil {
130-
return e.cause
134+
errs = append(errs, e.cause)
131135
}
132136

133-
return e.err
137+
return errs
134138
}
135139

136140
// Is reports whether e matches target. Two *Error values are considered equal
137141
// when their messages match and every field present in target also appears in
138142
// e with the same value. This allows errors.Is to find a sentinel Error
139143
// anywhere in a chain, optionally scoped by fields.
140144
//
141-
// Field values of different types never match. Uncomparable values are
142-
// compared with reflect.DeepEqual, so function fields only match when both are nil.
145+
// Field values of different types never match. Uncomparable values, including
146+
// comparable types holding an uncomparable dynamic value, are compared with
147+
// reflect.DeepEqual, so function fields only match when both are nil.
143148
func (e *Error) Is(target error) bool {
144149
var err *Error
145150
if e == nil || !errors.As(target, &err) || err == nil {
@@ -191,8 +196,8 @@ func (e *Error) StackTrace() []uintptr {
191196
return e.stack
192197
}
193198

194-
// Frames resolves the captured stack trace into call frames, outermost call first.
195-
// The sequence is empty when no stack was captured.
199+
// Frames resolves the captured stack trace into call frames, innermost call
200+
// first. The sequence is empty when no stack was captured.
196201
func (e *Error) Frames() iter.Seq[runtime.Frame] {
197202
return func(yield func(runtime.Frame) bool) {
198203
if e == nil || len(e.stack) == 0 {
@@ -212,13 +217,13 @@ func (e *Error) Frames() iter.Seq[runtime.Frame] {
212217
// details renders the message together with the fields, the cause and the
213218
// stack trace, as printed by the %+v verb.
214219
func (e *Error) details() string {
215-
b := &strings.Builder{}
216-
b.WriteString(e.Error())
217-
218220
if e == nil {
219-
return b.String()
221+
return e.Error()
220222
}
221223

224+
b := &strings.Builder{}
225+
b.WriteString(e.Error())
226+
222227
for _, k := range slices.Sorted(maps.Keys(e.data)) {
223228
fmt.Fprintf(b, "\n\t%s=%v", k, e.data[k])
224229
}
@@ -234,22 +239,23 @@ func (e *Error) details() string {
234239
return b.String()
235240
}
236241

237-
// callers returns up to 32 program counters starting skip frames above the caller.
242+
// callers returns up to 32 program counters starting skip frames above the
243+
// caller; deeper frames are dropped.
238244
func callers(skip int) []uintptr {
239245
stack := make([]uintptr, 32)
240246
n := runtime.Callers(skip+2, stack)
241247

242248
return stack[:n]
243249
}
244250

245-
// equal compares two field values without panicking on uncomparable types.
251+
// equal compares two field values without panicking on uncomparable types,
252+
// including comparable types that hold an uncomparable dynamic value.
246253
func equal(a, b any) bool {
247-
t := reflect.TypeOf(a)
248-
if t != reflect.TypeOf(b) {
254+
if reflect.TypeOf(a) != reflect.TypeOf(b) {
249255
return false
250256
}
251257

252-
if t == nil || t.Comparable() {
258+
if a == nil || (reflect.ValueOf(a).Comparable() && reflect.ValueOf(b).Comparable()) {
253259
return a == b
254260
}
255261

‎error_test.go‎

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ package errors
33
import (
44
"errors"
55
"fmt"
6-
"reflect"
6+
"io"
77
"slices"
88
"testing"
99

@@ -15,19 +15,15 @@ func TestNew(t *testing.T) {
1515

1616
assert.Equal(t, err.Error(), "test")
1717
assert.Empty(t, err.Fields())
18-
19-
cause := err.Unwrap()
20-
assert.Equal(t, reflect.TypeOf(cause).String(), "*errors.errorString")
18+
assert.Length(t, err.Unwrap(), 1)
2119
}
2220

2321
func TestNewf(t *testing.T) {
2422
err := Newf("Test Error #%d: %s", 5, "failed to spawn")
2523

2624
assert.Equal(t, err.Error(), "Test Error #5: failed to spawn")
2725
assert.Empty(t, err.Fields())
28-
29-
cause := err.Unwrap()
30-
assert.Equal(t, reflect.TypeOf(cause).String(), "*errors.errorString")
26+
assert.Length(t, err.Unwrap(), 1)
3127
}
3228

3329
func testMethod(err error) error {
@@ -51,9 +47,7 @@ func TestWrapStdError(t *testing.T) {
5147
err := Wrap(original)
5248

5349
assert.Equal(t, err.Error(), "original")
54-
55-
cause := errors.Unwrap(err)
56-
assert.Equal(t, cause, original)
50+
assert.Equal(t, err.Unwrap(), []error{original})
5751
}
5852

5953
func TestWrapError(t *testing.T) {
@@ -117,6 +111,22 @@ func TestFieldsUncomparableValues(t *testing.T) {
117111
assert.NotErrorIs(t, err1, err4)
118112
}
119113

114+
type container struct {
115+
value any
116+
}
117+
118+
func TestFieldsUncomparableDynamicValues(t *testing.T) {
119+
err1 := New("test").WithField("box", container{value: []int{1}})
120+
err2 := New("test").WithField("box", container{value: []int{1}})
121+
err3 := New("test").WithField("box", container{value: []int{2}})
122+
err4 := New("test").WithField("box", container{value: 1})
123+
124+
assert.ErrorIs(t, err1, err2)
125+
assert.NotErrorIs(t, err1, err3)
126+
assert.NotErrorIs(t, err1, err4)
127+
assert.ErrorIs(t, err4, New("test").WithField("box", container{value: 1}))
128+
}
129+
120130
func TestFieldsFunctionValues(t *testing.T) {
121131
callback := func() {}
122132

@@ -137,7 +147,7 @@ func TestNilReceiver(t *testing.T) {
137147
assert.NoError(t, err.WithField("action", "call"))
138148
assert.NoError(t, err.WithFields(map[string]any{"action": "call"}))
139149
assert.NoError(t, err.WithCause(New("cause")))
140-
assert.NoError(t, err.Unwrap())
150+
assert.Empty(t, err.Unwrap())
141151
assert.False(t, err.Is(New("test")))
142152
assert.NotErrorIs(t, New("test"), err)
143153
}
@@ -179,7 +189,22 @@ func TestWithCause(t *testing.T) {
179189
err2 := err1.WithCause(original)
180190

181191
assert.NotSame(t, err1, err2)
182-
assert.Same(t, err2.Unwrap(), original)
192+
assert.Equal(t, err2.Unwrap(), []error{err1.err, original})
193+
assert.ErrorIs(t, err2, original)
194+
}
195+
196+
func TestWithCauseKeepsWrappedError(t *testing.T) {
197+
cause := errors.New("cause")
198+
199+
err1 := Wrap(io.EOF).WithCause(cause)
200+
201+
assert.ErrorIs(t, err1, io.EOF)
202+
assert.ErrorIs(t, err1, cause)
203+
204+
err2 := Newf("read: %w", io.EOF).WithCause(cause)
205+
206+
assert.ErrorIs(t, err2, io.EOF)
207+
assert.ErrorIs(t, err2, cause)
183208
}
184209

185210
func TestErrorsIs(t *testing.T) {

‎wrap_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func TestWrapUnwrap(t *testing.T) {
1616
assert.Equal(t, Unwrap(inner), nil)
1717
assert.Equal(t, Unwrap(nil), nil)
1818

19-
var err *Error
19+
err := New("outer").WithCause(inner)
2020
assert.Equal(t, Unwrap(err), nil)
2121

2222
var errs *MultiError

0 commit comments

Comments
 (0)