Skip to content

Commit de10e10

Browse files
committed
Enhanced formatting for Error and MultiError
1 parent 1747c73 commit de10e10

9 files changed

Lines changed: 233 additions & 49 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,15 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
1010
### Added
1111
- `ErrUnsupported` re-exported from the standard library
1212
- `Error.GoString` and `%#v` print the error in Go syntax
13+
- `MultiError.Format` implements `fmt.Formatter`: `%+v` prints every collected error with its fields, stack trace and cause
1314

1415
### Changed
1516
- `Error.Unwrap` returns `[]error` holding both the wrapped error and the cause, so `errors.Unwrap` now returns nil for an `*Error` (**breaking**)
1617
- `Error.Is` matches on the underlying error identity instead of the message text, so two independent `New` calls with the same text no longer match (**breaking**)
1718
- `Error.Is` inspects only the target itself, no longer errors wrapped by the target (**breaking**)
19+
- `Error.Is` matches when the target's underlying error is anywhere in the chain of the inspected error's underlying error, so fields added after `Wrap` or `Newf` still scope a sentinel
20+
- `Wrap` and `Newf` with `%w` inherit the fields, cause and stack trace of an `*Error` found in the chain instead of capturing a new stack
21+
- `%+v` prints the stack trace before the cause
1822
- `Error.Format` honours width, precision and flags for `%s`, `%q`, `%v` and `%x`, and prints an `*Error` cause with `%+v` including its fields and stack trace
1923
- `MultiError.Unwrap` returns a copy of the collected errors
2024
- `MultiError.Errors` removed in favour of `MultiError.Unwrap` (**breaking**)
@@ -27,6 +31,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
2731
- `Error.Is` no longer matches a target field holding `nil` against an error that lacks the field
2832
- `Error.Is` no longer panics on a wrapped error of a comparable type holding an uncomparable dynamic value
2933
- `MultiError.Error` no longer panics on a nil receiver and no longer holds the lock while formatting collected errors
34+
- `Error.Is` no longer matches two zero-value `Error` values
3035

3136

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

‎README.md‎

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,17 @@ err := errors.Newf("user %d missing", 42)
5252
err = errors.Wrap(io.EOF) // *Error with a stack trace, an *Error is returned unchanged
5353
```
5454

55+
Adding context keeps everything the error already carries:
56+
57+
```go
58+
err := ErrNotFound.WithField("id", 42)
59+
err = errors.Newf("load user: %w", err) // fields, cause and stack are inherited
60+
err = errors.Wrap(fmt.Errorf("handler: %w", err))
61+
62+
err.Fields() // map[id:42]
63+
errors.Is(err, ErrNotFound.WithField("id", 42)) // true
64+
```
65+
5566
Fields and causes:
5667

5768
```go
@@ -117,15 +128,27 @@ errs.Len() // 2
117128
errors.Is(errs, errA) // true, every collected error is inspected
118129
```
119130

120-
Printing, the message alone with `%v`, or the fields, the cause and the stack trace with `%+v`:
131+
Printing, the message alone with `%v`, or the fields, the stack trace and the cause with `%+v`:
121132

122133
```go
123134
fmt.Printf("%+v", err)
124135
// process failed
125136
// process=abc
126-
// caused by: connection refused
127137
// main.Process
128138
// /app/main.go:14
139+
// caused by: connection refused
140+
```
141+
142+
A multi error prints every collected error the same way:
143+
144+
```go
145+
fmt.Printf("%+v", errs)
146+
// 2 errors occurred:
147+
// process failed
148+
// process=abc
149+
// main.Process
150+
// /app/main.go:14
151+
// connection refused
129152
```
130153

131154
Walking the captured stack:
@@ -148,21 +171,23 @@ errors its message is a numbered summary rather than the errors joined by newlin
148171
Use `Is` and `As` to inspect the chain. An `Error` unwraps to its underlying error followed by its cause, so attaching
149172
a cause never hides the wrapped error.
150173

151-
**Equality:** Two `*Error` values match under `Is` when they share the same underlying error and every field of the
152-
target is present in the inspected error with the same value. Only the target itself is inspected, never the errors it
153-
wraps. Field values of different types never match, uncomparable values fall back to `reflect.DeepEqual`, and an
154-
underlying error of an uncomparable type never matches.
174+
**Equality:** Two `*Error` values match under `Is` when the underlying error of the target is found in the chain of
175+
the underlying error of the inspected error, and every field of the target is present in the inspected error with the
176+
same value. Only the target itself is inspected, never its cause nor the errors it wraps. Field values of different
177+
types never match, uncomparable values fall back to `reflect.DeepEqual`, and an underlying error of an uncomparable
178+
type never matches.
155179

156180
**Typed nil:** `Wrap` returns `*Error` so that fields can be chained onto it. `Wrap(nil)` therefore returns a typed nil
157181
pointer, which is not equal to `nil` once stored in an `error`. Chaining `WithField`, `WithFields` or `WithCause` on it
158182
is safe and yields `nil` again, but the result must not be returned as an `error`.
159183

160184
**Formatting:** `%s`, `%q`, `%x` and `%v` print the message and honour width, precision and flags. `%+v` adds the
161-
fields sorted by key, the cause formatted with `%+v` as well, and the stack trace innermost call first. `%#v` prints
162-
the error in Go syntax.
185+
fields sorted by key, the stack trace innermost call first, and the cause formatted with `%+v` as well. `%#v` prints
186+
the error in Go syntax. `MultiError` formats the same way, printing every collected error with the verb it was given.
163187

164188
**Stack traces:** `New`, `Newf` and `Wrap` capture up to 32 frames above the caller. `With*` methods keep the stack of
165-
the error they derive from, and wrapping an `*Error` keeps its original stack.
189+
the error they derive from. When `Wrap` or `Newf` with `%w` find an `*Error` in the chain, they inherit its fields,
190+
cause and stack instead of capturing a new one, so context can be added at every layer without losing anything.
166191

167192
**Multi error:** `Add` skips `nil` errors, `Unwrap` returns a copy safe to modify, and all methods are safe for
168193
concurrent use. A single collected error reports its message unchanged. `ErrorOrNil` is the only way to obtain a

‎error.go‎

Lines changed: 51 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package errors
33
import (
44
"errors"
55
"fmt"
6-
"io"
76
"iter"
87
"maps"
98
"reflect"
@@ -30,17 +29,18 @@ func New(text string) *Error {
3029
}
3130
}
3231

33-
// Newf creates an Error from a formatted string and captures the current stack trace.
32+
// Newf creates an Error from a formatted string. When the format wraps an
33+
// *Error with %w, its fields, cause and stack trace are inherited, so adding
34+
// context to an error never hides what it already carries. Otherwise the
35+
// current stack trace is captured.
3436
func Newf(format string, v ...any) *Error {
35-
return &Error{
36-
err: fmt.Errorf(format, v...),
37-
stack: callers(1),
38-
}
37+
return derive(fmt.Errorf(format, v...))
3938
}
4039

41-
// Wrap converts an error into an *Error and captures the current stack trace.
42-
// If err is nil, Wrap returns nil. If err is already an *Error it is returned
43-
// unchanged. Otherwise the error is wrapped directly.
40+
// Wrap converts an error into an *Error. If err is nil, Wrap returns nil. If
41+
// err is already an *Error it is returned unchanged. If an *Error is found in
42+
// the chain of err, its fields, cause and stack trace are inherited. Otherwise
43+
// the current stack trace is captured.
4444
//
4545
// Warning: the returned *Error nil is a typed nil pointer. When assigned to
4646
// or returned as an error interface it will not equal nil. Prefer checking the
@@ -54,9 +54,26 @@ func Wrap(err error) *Error {
5454
return dataErr
5555
}
5656

57+
return derive(err)
58+
}
59+
60+
// derive builds an Error around err, inheriting the fields, cause and stack
61+
// trace of the first *Error found in its chain. When there is none the stack
62+
// trace is captured two frames above, at the caller of the exported function.
63+
func derive(err error) *Error {
64+
inner, ok := AsType[*Error](err)
65+
if !ok || inner == nil {
66+
return &Error{
67+
err: err,
68+
stack: callers(2),
69+
}
70+
}
71+
5772
return &Error{
5873
err: err,
59-
stack: callers(1),
74+
data: inner.data,
75+
cause: inner.cause,
76+
stack: inner.stack,
6077
}
6178
}
6279

@@ -146,24 +163,26 @@ func (e *Error) Unwrap() []error {
146163
return errs
147164
}
148165

149-
// Is reports whether e matches target. Two *Error values match when they share
150-
// the same underlying error and every field present in target also appears in
151-
// e with the same value. WithField, WithFields and WithCause keep the underlying
152-
// error, so errors.Is finds a sentinel Error anywhere in a chain, optionally
153-
// scoped by fields. Only target itself is inspected; errors wrapped by target
154-
// are not.
166+
// Is reports whether e matches target. Two *Error values match when the
167+
// underlying error of target is found in the chain of the underlying error of
168+
// e, and every field present in target also appears in e with the same value.
169+
// WithField, WithFields and WithCause keep the underlying error, and Wrap and
170+
// Newf keep it in the chain, so errors.Is finds a sentinel Error anywhere,
171+
// optionally scoped by fields. Only target itself is inspected; neither its
172+
// cause nor the errors wrapped by it are.
155173
//
156174
// Field values of different types never match. Uncomparable values, including
157175
// comparable types holding an uncomparable dynamic value, are compared with
158176
// reflect.DeepEqual, so function fields only match when both are nil.
159-
// Underlying errors of an uncomparable type never match.
177+
// Underlying errors of an uncomparable type never match, and neither does a
178+
// zero-value Error.
160179
func (e *Error) Is(target error) bool {
161180
err, ok := target.(*Error)
162181
if !ok || e == nil || err == nil {
163182
return false
164183
}
165184

166-
if !same(e.err, err.err) {
185+
if !contains(e.err, err.err) {
167186
return false
168187
}
169188

@@ -179,17 +198,10 @@ func (e *Error) Is(target error) bool {
179198

180199
// Format implements fmt.Formatter. The message is printed like a plain string,
181200
// so %s, %q, %x and %v honour width, precision and flags. %+v additionally
182-
// prints the fields, the cause chain and the stack trace, formatting the cause
201+
// prints the fields, the stack trace and the cause chain, formatting the cause
183202
// with %+v as well, and %#v prints the error in Go syntax.
184203
func (e *Error) Format(s fmt.State, verb rune) {
185-
switch {
186-
case verb == 'v' && s.Flag('+'):
187-
io.WriteString(s, e.details())
188-
case verb == 'v' && s.Flag('#'):
189-
io.WriteString(s, e.GoString())
190-
default:
191-
fmt.Fprintf(s, fmt.FormatString(s, verb), e.Error())
192-
}
204+
format(e, s, verb)
193205
}
194206

195207
// GoString implements fmt.GoStringer for debugging output.
@@ -229,8 +241,8 @@ func (e *Error) Frames() iter.Seq[runtime.Frame] {
229241
}
230242
}
231243

232-
// details renders the message together with the fields, the cause and the
233-
// stack trace, as printed by the %+v verb.
244+
// details renders the message together with the fields, the stack trace and
245+
// the cause, as printed by the %+v verb.
234246
func (e *Error) details() string {
235247
if e == nil {
236248
return e.Error()
@@ -243,14 +255,14 @@ func (e *Error) details() string {
243255
fmt.Fprintf(b, "\n\t%s=%v", k, e.data[k])
244256
}
245257

246-
if e.cause != nil {
247-
fmt.Fprintf(b, "\ncaused by: %+v", e.cause)
248-
}
249-
250258
for frame := range e.Frames() {
251259
fmt.Fprintf(b, "\n\t%s\n\t\t%s:%d", frame.Function, frame.File, frame.Line)
252260
}
253261

262+
if e.cause != nil {
263+
fmt.Fprintf(b, "\ncaused by: %+v", e.cause)
264+
}
265+
254266
return b.String()
255267
}
256268

@@ -282,13 +294,13 @@ func equal(a, b any) bool {
282294
return reflect.DeepEqual(a, b)
283295
}
284296

285-
// same reports whether two errors are the identical value. Errors holding an
286-
// uncomparable value, including comparable types with an uncomparable dynamic
287-
// value, are never the same, so the comparison cannot panic.
288-
func same(a, b error) bool {
289-
if a != nil && !reflect.ValueOf(a).Comparable() {
297+
// contains reports whether target is found in the chain of err. A nil target
298+
// or one holding an uncomparable value, including a comparable type with an
299+
// uncomparable dynamic value, is never found, so the comparison cannot panic.
300+
func contains(err, target error) bool {
301+
if target == nil || !reflect.ValueOf(target).Comparable() {
290302
return false
291303
}
292304

293-
return a == b
305+
return errors.Is(err, target)
294306
}

‎error_test.go‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,46 @@ func TestWrapError(t *testing.T) {
5858
assert.Same(t, err, original)
5959
}
6060

61+
func TestWrapInherits(t *testing.T) {
62+
inner := New("inner").WithField("id", 42).WithCause(io.EOF)
63+
outer := Wrap(fmt.Errorf("ctx: %w", inner))
64+
65+
assert.Equal(t, outer.Error(), "ctx: inner")
66+
assert.Equal(t, outer.Fields(), map[string]any{"id": 42})
67+
assert.Equal(t, outer.StackTrace(), inner.StackTrace())
68+
assert.Equal(t, outer.Unwrap()[1], io.EOF)
69+
assert.ErrorIs(t, outer, inner)
70+
assert.ErrorIs(t, outer, inner.WithField("id", 42))
71+
assert.NotErrorIs(t, outer, inner.WithField("id", 7))
72+
assert.ErrorIs(t, outer, io.EOF)
73+
74+
found, ok := AsType[*Error](outer)
75+
76+
assert.True(t, ok)
77+
assert.Same(t, found, outer)
78+
}
79+
80+
func TestWrapInheritsTypedNil(t *testing.T) {
81+
var inner *Error
82+
outer := Wrap(fmt.Errorf("ctx: %w", inner))
83+
84+
assert.Equal(t, outer.Error(), "ctx: <nil>")
85+
assert.Empty(t, outer.Fields())
86+
assert.NotEmpty(t, outer.StackTrace())
87+
}
88+
89+
func TestNewfInherits(t *testing.T) {
90+
inner := New("inner").WithField("id", 42)
91+
outer := Newf("ctx %d: %w", 1, inner).WithField("attempt", 3)
92+
93+
assert.Equal(t, outer.Error(), "ctx 1: inner")
94+
assert.Equal(t, outer.Fields(), map[string]any{"id": 42, "attempt": 3})
95+
assert.Equal(t, outer.StackTrace(), inner.StackTrace())
96+
assert.ErrorIs(t, outer, inner.WithField("id", 42))
97+
assert.ErrorIs(t, outer, inner.WithField("attempt", 3))
98+
assert.NotErrorIs(t, inner, outer)
99+
}
100+
61101
func TestStackTrace(t *testing.T) {
62102
err1 := New("test")
63103
err2 := Newf("test %d", 1)
@@ -178,6 +218,8 @@ func TestZeroValue(t *testing.T) {
178218
assert.Equal(t, err.Error(), "<nil>")
179219
assert.Empty(t, err.Unwrap())
180220
assert.NotErrorIs(t, &err, errors.New("test"))
221+
assert.NotErrorIs(t, &err, &Error{})
222+
assert.NotErrorIs(t, New("test"), &err)
181223
}
182224

183225
func TestWithFieldsEmpty(t *testing.T) {
@@ -250,13 +292,14 @@ func TestFormat(t *testing.T) {
250292

251293
func TestFormatNestedCause(t *testing.T) {
252294
inner := New("inner").WithField("layer", 1)
253-
outer := New("outer").WithCause(inner)
295+
outer := New("outer").WithField("layer", 0).WithCause(inner)
254296

255297
details := fmt.Sprintf("%+v", outer)
256298

257299
assert.Contains(t, details, "caused by: inner")
258300
assert.Contains(t, details, "layer=1")
259301
assert.Equal(t, strings.Count(details, "github.com/gravitton/errors.TestFormatNestedCause"), 2)
302+
assert.Matches(t, details, `^outer\n\tlayer=0\n\t[^\n]+TestFormatNestedCause\n(\t[^\n]+\n)*caused by: inner\n\tlayer=1\n\t[^\n]+TestFormatNestedCause\n`)
260303
}
261304

262305
func TestFormatFlags(t *testing.T) {
@@ -361,5 +404,7 @@ func TestErrorsIsInspectsOnlyTarget(t *testing.T) {
361404
assert.NotErrorIs(t, sentinel, fmt.Errorf("wrapped: %w", sentinel))
362405
assert.NotErrorIs(t, sentinel, Join(errors.New("other"), sentinel))
363406
assert.NotErrorIs(t, sentinel, New("other").WithCause(sentinel))
407+
assert.NotErrorIs(t, sentinel, Newf("wrapped: %w", sentinel))
364408
assert.ErrorIs(t, New("other").WithCause(sentinel), sentinel)
409+
assert.ErrorIs(t, sentinel, sentinel.WithCause(io.EOF))
365410
}

‎format.go‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package errors
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"strings"
7+
)
8+
9+
// detailed is an error that can render itself with the fields, causes and
10+
// stack traces it carries, as printed by the %+v verb.
11+
type detailed interface {
12+
error
13+
fmt.GoStringer
14+
details() string
15+
}
16+
17+
// format implements fmt.Formatter for a detailed error. The message is printed
18+
// like a plain string, so %s, %q, %x and %v honour width, precision and flags.
19+
// %+v prints the details and %#v prints the error in Go syntax.
20+
func format(e detailed, s fmt.State, verb rune) {
21+
switch {
22+
case verb == 'v' && s.Flag('+'):
23+
io.WriteString(s, e.details())
24+
case verb == 'v' && s.Flag('#'):
25+
io.WriteString(s, e.GoString())
26+
default:
27+
fmt.Fprintf(s, fmt.FormatString(s, verb), e.Error())
28+
}
29+
}
30+
31+
// indent prefixes every line of text with a tab.
32+
func indent(text string) string {
33+
return "\t" + strings.ReplaceAll(text, "\n", "\n\t")
34+
}

0 commit comments

Comments
 (0)