Skip to content

Commit 4ae7a7a

Browse files
committed
Improve formatting, refine WithField, stack behavior
1 parent eba8be6 commit 4ae7a7a

10 files changed

Lines changed: 211 additions & 85 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,17 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
1010
### Added
1111
- `Sentinel` creates an `*Error` without a stack trace, meant for package-level errors
1212
- `ErrUnsupported` re-exported from the standard library
13-
- `Error.GoString` and `MultiError.GoString` print the error in Go syntax, used by `%#v`
13+
- `Error.GoString` and `MultiError.GoString` print the error and every contained error in Go syntax, used by `%#v`
1414
- `MultiError.Format` implements `fmt.Formatter`: `%+v` prints every collected error with `%+v`
15+
- Runnable examples of the error messages, fields, causes and collections
1516

1617
### Changed
1718
- `Wrap`, `Newf`, `Error.Fields` and `%+v` look through single-error wrappers for inner `*Error` values: the first stack trace found is reused, fields are merged with the outermost value winning, and every cause is printed
18-
- `Wrap` gives a stackless `*Error` the current stack trace
19+
- `Wrap`, `Error.WithField`, `Error.WithFields` and `Error.WithCause` give a stackless `*Error` the current stack trace
1920
- `Error.WithCause` appends to the causes instead of replacing the cause (**breaking**)
2021
- `Error.Unwrap` returns `[]error` holding the underlying error and the causes, so `errors.Unwrap` returns nil for an `*Error` (**breaking**)
2122
- `Error.Is` matches when the target's underlying error is in the chain of the underlying error, instead of comparing the message and fields, so fields no longer scope a match and two `New` calls with the same text no longer match (**breaking**)
22-
- `Error.Format` honors width, precision and flags for `%s`, `%q`, `%v` and `%x`, and `%+v` prints the causes with `%+v` after the stack trace
23+
- `Error.Format` honors width, precision and flags for `%s`, `%q`, `%v` and `%x`, and `%+v` prints the causes with `%+v` after the stack trace, each indented one level
2324
- `Error.StackTrace` and `MultiError.Unwrap` return copies
2425
- `MultiError.Error` indents every message with a tab and reports `no errors` for an empty collection (**breaking**)
2526
- Methods of `Error` and `MultiError` no longer handle nil receivers (**breaking**)
@@ -29,7 +30,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
2930
- `MultiError.Errors`, use `MultiError.Unwrap` instead (**breaking**)
3031

3132

32-
## v1.3.0 (2026-08-26)(https://github.com/gravitton/errors/compare/v1.2.1...v1.3.0)
33+
## [v1.3.0](https://github.com/gravitton/errors/compare/v1.2.1...v1.3.0) (2026-08-26)
3334
### Added
3435
- `Error.Format` implements `fmt.Formatter`: `%+v` prints fields, cause and stack trace
3536
- `Error.Frames` iterator resolving the captured stack trace into `runtime.Frame` values
@@ -48,23 +49,23 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
4849
- `Error.Error`, `Fields`, `StackTrace` and `Is` now handle a nil receiver safely
4950

5051

51-
## v1.2.1 (2026-05-21)(https://github.com/gravitton/errors/compare/v1.2.0...v1.2.1)
52+
## [v1.2.1](https://github.com/gravitton/errors/compare/v1.2.0...v1.2.1) (2026-05-21)
5253
### Fixed
5354
- `DataError.Unwrap` now handles nil receiver safely, preventing a panic when a typed-nil `*DataError` is passed to `errors.Unwrap`, `errors.Is`, or `errors.As`
5455

5556

56-
## v1.2.0 (2026-05-14)(https://github.com/gravitton/errors/compare/v1.1.1...v1.2.0)
57+
## [v1.2.0](https://github.com/gravitton/errors/compare/v1.1.1...v1.2.0) (2026-05-14)
5758
### Added
5859
- `AsType[T]` generic wrapper for `errors.AsType` (Go 1.26)
5960
- `Join` constructor to build a `MultiError` from a variadic list of errors
6061

6162

62-
## v1.1.1 (2026-04-23)(https://github.com/gravitton/errors/compare/v1.01.0...v1.1.1)
63+
## [v1.1.1](https://github.com/gravitton/errors/compare/v1.1.0...v1.1.1) (2026-04-23)
6364
### Changed
6465
- `Wrap` now accepts only `error` instead of `any`
6566

6667

67-
## v1.1.0 (2026-04-22)(https://github.com/gravitton/errors/compare/v1.0.0...v1.1.0)
68+
## [v1.1.0](https://github.com/gravitton/errors/compare/v1.0.0...v1.1.0) (2026-04-22)
6869
### Added
6970
- `DataError` stack trace capture via `StackTrace()`
7071

‎README.md‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ go get github.com/gravitton/errors
4646
Creating and wrapping:
4747

4848
```go
49-
var ErrNotFound = errors.Sentinel("not found") // no stack trace, captured when wrapped
49+
var ErrNotFound = errors.Sentinel("not found") // no stack trace, captured when derived or wrapped
5050

5151
err := errors.New("boom") // *Error with a stack trace
5252
err = errors.Newf("user %d missing", 42)
@@ -55,13 +55,14 @@ err = errors.Wrap(err) // an *Error with a stack trace
5555
```
5656

5757
Use `Sentinel`, not `New`, for package-level errors: `New` captures the stack where it is called, and at package
58-
initialisation that stack points nowhere useful.
58+
initialisation that stack points nowhere useful. For the same reason, don't derive package-level errors with
59+
`WithField` or `WithCause`.
5960

6061
Adding context at every layer keeps what was added before:
6162

6263
```go
63-
err := errors.Wrap(ErrNotFound.WithField("id", 42)) // the stack trace is captured here
64-
err = errors.Newf("load user: %w", err) // the stack trace is reused
64+
err := ErrNotFound.WithField("id", 42) // the stack trace is captured here
65+
err = errors.Newf("load user: %w", err) // the stack trace is reused
6566
err = errors.Wrap(fmt.Errorf("handler: %w", err)).WithField("handler", "users")
6667

6768
err.Fields() // map[handler:users id:42]
@@ -146,9 +147,17 @@ fmt.Printf("%+v", err)
146147
// process=abc
147148
// main.Process
148149
// /app/main.go:14
149-
// caused by: connection refused
150+
// caused by: could not dial
151+
// main.dial
152+
// /app/main.go:27
153+
// caused by: connection refused
150154
```
151155

156+
Each cause is indented one level, so the cause of a cause is told apart from its siblings.
157+
158+
`%+v` only reaches the fields and the stack trace when the outermost error is an `*Error`: `fmt.Errorf` does not
159+
implement `fmt.Formatter`, so `fmt.Errorf("handler: %w", err)` prints the message alone. Wrap it, or use `Newf`.
160+
152161
Full reference: [pkg.go.dev][link-go-dev-reference].
153162

154163
## Conventions

‎doc.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
// Package errors provides an extended error type with structured key-value
2-
// fields, stack traces, and cause chaining, along with a thread-safe
3-
// multi-error container. It is a drop-in superset of the standard library
4-
// errors package: Unwrap, Is, As, and AsType are re-exported so callers only
5-
// need to import this package.
1+
// Package errors provides an error type with key-value fields, causes, and a
2+
// stack trace, along with a multi-error collection safe for concurrent use. It
3+
// is a drop-in superset of the standard library errors package: Unwrap, Is, As,
4+
// AsType, and ErrUnsupported are re-exported and Join returns a MultiError, so
5+
// callers only need to import this package.
66
package errors

‎error.go‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,14 @@ func New(text string) *Error {
2626
}
2727

2828
// Sentinel creates an Error without a stack trace, meant for package-level errors.
29-
// The stack trace is captured where it is passed to Wrap or wrapped by Newf.
29+
// The stack trace is captured where the error is derived or wrapped.
3030
func Sentinel(text string) *Error {
3131
return &Error{
3232
err: errors.New(text),
3333
}
3434
}
3535

36-
// Newf creates an Error from fmt.Errorf, like Wrap does.
36+
// Newf formats an error with fmt.Errorf and wraps it like Wrap does.
3737
func Newf(format string, args ...any) *Error {
3838
return wrap(fmt.Errorf(format, args...))
3939
}
@@ -101,13 +101,19 @@ func (e *Error) Fields() map[string]any {
101101
return fields
102102
}
103103

104-
// WithField returns a copy of the error with the field added.
104+
// WithField returns a copy of the error with the field added. A copy of an error
105+
// without a stack trace gets the current one.
105106
func (e *Error) WithField(key string, value any) *Error {
106-
return e.WithFields(map[string]any{key: value})
107+
return wrap(e).withFields(map[string]any{key: value})
107108
}
108109

109-
// WithFields returns a copy of the error with the fields added.
110+
// WithFields returns a copy of the error with the fields added. A copy of an error
111+
// without a stack trace gets the current one.
110112
func (e *Error) WithFields(fields map[string]any) *Error {
113+
return wrap(e).withFields(fields)
114+
}
115+
116+
func (e *Error) withFields(fields map[string]any) *Error {
111117
derived := *e
112118
derived.fields = make(map[string]any, len(e.fields)+len(fields))
113119
maps.Copy(derived.fields, e.fields)
@@ -116,14 +122,14 @@ func (e *Error) WithFields(fields map[string]any) *Error {
116122
return &derived
117123
}
118124

119-
// WithCause returns a copy of the error with the cause appended. A nil cause
120-
// returns the error unchanged.
125+
// WithCause returns a copy of the error with the cause appended. A copy of an error
126+
// without a stack trace gets the current one. A nil cause returns the error unchanged.
121127
func (e *Error) WithCause(cause error) *Error {
122128
if cause == nil {
123129
return e
124130
}
125131

126-
derived := *e
132+
derived := *wrap(e)
127133
derived.causes = append(slices.Clip(e.causes), cause)
128134

129135
return &derived
@@ -143,7 +149,7 @@ func (e *Error) Format(s fmt.State, verb rune) {
143149

144150
// GoString returns the error in Go syntax.
145151
func (e *Error) GoString() string {
146-
return fmt.Sprintf("&errors.Error{err:%#v, fields:%#v, causes:%#v}", e.err, e.fields, e.causes)
152+
return fmt.Sprintf("&errors.Error{err:%#v, fields:%#v, causes:%s}", e.err, e.fields, goSyntax(e.causes))
147153
}
148154

149155
func (e *Error) details() string {
@@ -161,7 +167,7 @@ func (e *Error) details() string {
161167

162168
for inner := range mainChain(e) {
163169
for _, cause := range inner.causes {
164-
fmt.Fprintf(b, "\ncaused by: %+v", cause)
170+
fmt.Fprintf(b, "\ncaused by: %s", indent(fmt.Sprintf("%+v", cause)))
165171
}
166172
}
167173

‎error_test.go‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,9 @@ func TestWrapErrorWithStack(t *testing.T) {
8686
}
8787

8888
func TestWrapSentinel(t *testing.T) {
89-
err := Wrap(errSentinel.WithField("id", 1))
89+
err := Wrap(errSentinel)
9090

9191
assert.Equal(t, raisedIn(err), "TestWrapSentinel")
92-
assert.Equal(t, err.Fields(), map[string]any{"id": 1})
9392
assert.ErrorIs(t, err, errSentinel)
9493
assert.Empty(t, errSentinel.StackTrace())
9594
}
@@ -140,6 +139,21 @@ func TestWithFields(t *testing.T) {
140139
assert.Equal(t, err.Fields(), map[string]any{"a": 2, "b": 3})
141140
}
142141

142+
func TestWithFieldsCopiesMap(t *testing.T) {
143+
fields := map[string]any{"a": 1}
144+
err := New("test").WithFields(fields)
145+
fields["a"] = 2
146+
147+
assert.Equal(t, err.Fields(), map[string]any{"a": 1})
148+
}
149+
150+
func TestDerivedSentinelCapturesStack(t *testing.T) {
151+
assert.Equal(t, raisedIn(errSentinel.WithField("a", 1)), "TestDerivedSentinelCapturesStack")
152+
assert.Equal(t, raisedIn(errSentinel.WithFields(map[string]any{"a": 1})), "TestDerivedSentinelCapturesStack")
153+
assert.Equal(t, raisedIn(errSentinel.WithCause(io.EOF)), "TestDerivedSentinelCapturesStack")
154+
assert.Empty(t, errSentinel.StackTrace())
155+
}
156+
143157
func TestFieldsMergeMainChain(t *testing.T) {
144158
inner := New("inner").WithFields(map[string]any{"a": 1, "b": 1})
145159
err := Wrap(fmt.Errorf("outer: %w", inner)).WithField("b", 2)
@@ -228,15 +242,24 @@ func TestFormat(t *testing.T) {
228242
assert.Equal(t, fmt.Sprintf("%v", err), "test")
229243
assert.Equal(t, fmt.Sprintf("%q", err), `"test"`)
230244
assert.Equal(t, fmt.Sprintf("[%6s]", err), "[ test]")
231-
assert.Equal(t, fmt.Sprintf("%#v", err), `&errors.Error{err:&errors.errorString{s:"test"}, fields:map[string]interface {}{"a":1}, causes:[]error(nil)}`)
245+
assert.Equal(t, fmt.Sprintf("%#v", err), `&errors.Error{err:&errors.errorString{s:"test"}, fields:map[string]interface {}{"a":1}, causes:[]error{}}`)
246+
assert.Equal(t, fmt.Sprintf("%#v", errSentinel.WithCause(io.EOF)), `&errors.Error{err:&errors.errorString{s:"sentinel"}, fields:map[string]interface {}(nil), causes:[]error{&errors.errorString{s:"EOF"}}}`)
232247
}
233248

234249
func TestFormatDetails(t *testing.T) {
235-
err := New("test").WithField("b", 2).WithField("a", 1).WithCause(io.EOF)
250+
err := New("test").WithField("b", 2).WithField("a", 1).WithCause(io.EOF).WithCause(io.ErrClosedPipe)
236251
details := fmt.Sprintf("%+v", err)
237252

238253
assert.True(t, strings.HasPrefix(details, "test\n\ta=1\n\tb=2\n\tgithub.com/gravitton/errors.TestFormatDetails\n\t\t"))
239-
assert.True(t, strings.HasSuffix(details, "\ncaused by: EOF"))
254+
assert.True(t, strings.HasSuffix(details, "\ncaused by: EOF\ncaused by: io: read/write on closed pipe"))
255+
}
256+
257+
func TestFormatDetailsNestedCauses(t *testing.T) {
258+
err := New("root").WithCause(New("a").WithCause(io.EOF)).WithCause(io.ErrClosedPipe)
259+
details := fmt.Sprintf("%+v", err)
260+
261+
assert.True(t, strings.Contains(details, "\ncaused by: a\n\t\tgithub.com/gravitton/errors.TestFormatDetailsNestedCauses\n\t\t\t"))
262+
assert.True(t, strings.HasSuffix(details, "\n\tcaused by: EOF\ncaused by: io: read/write on closed pipe"))
240263
}
241264

242265
func TestFormatDetailsNested(t *testing.T) {
@@ -256,5 +279,5 @@ func TestFormatDetailsUnderlyingMessageOnly(t *testing.T) {
256279
}
257280

258281
func TestFormatDetailsSentinel(t *testing.T) {
259-
assert.Equal(t, fmt.Sprintf("%+v", errSentinel.WithField("a", 1)), "sentinel\n\ta=1")
282+
assert.Equal(t, fmt.Sprintf("%+v", errSentinel), "sentinel")
260283
}

‎example_test.go‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
package errors_test
2+
3+
import (
4+
"fmt"
5+
"io"
6+
7+
"github.com/gravitton/errors"
8+
)
9+
10+
var ErrNotFound = errors.Sentinel("not found")
11+
12+
func ExampleNew() {
13+
err := errors.New("boom")
14+
15+
fmt.Printf("%v\n", err)
16+
fmt.Printf("%q\n", err)
17+
fmt.Printf("%#v\n", err)
18+
// Output:
19+
// boom
20+
// "boom"
21+
// &errors.Error{err:&errors.errorString{s:"boom"}, fields:map[string]interface {}(nil), causes:[]error{}}
22+
}
23+
24+
func ExampleNewf() {
25+
err := errors.Newf("load user %d: %w", 42, ErrNotFound)
26+
27+
fmt.Println(err)
28+
// Output:
29+
// load user 42: not found
30+
}
31+
32+
func ExampleWrap() {
33+
err := errors.Wrap(io.EOF)
34+
35+
fmt.Printf("%v\n", err)
36+
fmt.Printf("%#v\n", err)
37+
// Output:
38+
// EOF
39+
// &errors.Error{err:&errors.errorString{s:"EOF"}, fields:map[string]interface {}(nil), causes:[]error{}}
40+
}
41+
42+
func ExampleError_Fields() {
43+
err := ErrNotFound.WithFields(map[string]any{"id": 42, "table": "users"})
44+
err = errors.Newf("load user: %w", err)
45+
err = errors.Wrap(fmt.Errorf("handler: %w", err)).WithField("table", "accounts")
46+
47+
fmt.Println(err)
48+
fmt.Println(err.Fields())
49+
// Output:
50+
// handler: load user: not found
51+
// map[id:42 table:accounts]
52+
}
53+
54+
func ExampleError_WithCause() {
55+
cause := errors.New("connection refused").WithField("port", 5432)
56+
err := errors.New("could not load config").WithCause(cause).WithCause(io.ErrClosedPipe)
57+
58+
fmt.Printf("%v\n", err)
59+
fmt.Printf("%#v\n", err)
60+
// Output:
61+
// could not load config
62+
// &errors.Error{err:&errors.errorString{s:"could not load config"}, fields:map[string]interface {}(nil), causes:[]error{&errors.Error{err:&errors.errorString{s:"connection refused"}, fields:map[string]interface {}{"port":5432}, causes:[]error{}}, &errors.errorString{s:"io: read/write on closed pipe"}}}
63+
}
64+
65+
func ExampleJoin() {
66+
fmt.Println(errors.Join(nil, nil))
67+
fmt.Println(errors.Join(io.EOF, nil))
68+
fmt.Println(errors.Join(io.EOF, errors.New("line one\nline two"), io.ErrClosedPipe))
69+
// Output:
70+
// <nil>
71+
// EOF
72+
// 3 errors occurred:
73+
// EOF
74+
// line one
75+
// line two
76+
// io: read/write on closed pipe
77+
}
78+
79+
func ExampleMultiError() {
80+
errs := errors.NewMulti()
81+
fmt.Println(errs.ErrorOrNil())
82+
83+
errs.Add(nil, io.EOF)
84+
errs.Add(errors.Join(io.ErrUnexpectedEOF, io.ErrClosedPipe))
85+
86+
fmt.Printf("%v\n", errs)
87+
fmt.Printf("%#v\n", errs)
88+
// Output:
89+
// <nil>
90+
// 2 errors occurred:
91+
// EOF
92+
// 2 errors occurred:
93+
// unexpected EOF
94+
// io: read/write on closed pipe
95+
// &errors.MultiError{errs:[]error{&errors.errorString{s:"EOF"}, &errors.MultiError{errs:[]error{&errors.errorString{s:"unexpected EOF"}, &errors.errorString{s:"io: read/write on closed pipe"}}}}}
96+
}

‎format.go‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package errors
33
import (
44
"fmt"
55
"io"
6+
"strings"
67
)
78

89
type detailed interface {
@@ -21,3 +22,16 @@ func format(e detailed, s fmt.State, verb rune) {
2122
fmt.Fprintf(s, fmt.FormatString(s, verb), e.Error())
2223
}
2324
}
25+
26+
func goSyntax(errs []error) string {
27+
items := make([]string, len(errs))
28+
for i, err := range errs {
29+
items[i] = fmt.Sprintf("%#v", err)
30+
}
31+
32+
return "[]error{" + strings.Join(items, ", ") + "}"
33+
}
34+
35+
func indent(text string) string {
36+
return strings.ReplaceAll(text, "\n", "\n\t")
37+
}

0 commit comments

Comments
 (0)