Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 57 additions & 2 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,13 +109,68 @@ func New(message string) error {
// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
// Errorf also records the stack trace at the point it was called.
// If the format specifier includes a %w verb with an error operand,
// the returned error will implement an Unwrap method returning the operand.
func Errorf(format string, args ...interface{}) error {
return &fundamental{
msg: fmt.Sprintf(format, args...),
err := fmt.Errorf(format, args...)
f := &fundamental{
msg: err.Error(),
stack: callers(),
}
switch u := err.(type) {
case interface{ Unwrap() error }:
if unwrapped := u.Unwrap(); unwrapped != nil {
return &wrapError{
fundamental: f,
err: unwrapped,
}
}
case interface{ Unwrap() []error }:
errs := u.Unwrap()
switch len(errs) {
case 0:
case 1:
if errs[0] != nil {
return &wrapError{
fundamental: f,
err: errs[0],
}
}
default:
return &wrapErrors{
fundamental: f,
errs: errs,
}
}
}
return f
}

type wrapError struct {
*fundamental
err error
}
Comment on lines +149 to +152

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why recreate &withMessage{ cause: &fundamental{ … } }?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in eae2cc5: wrapError now embeds *fundamental to reuse Error(), Format(), and StackTrace() without duplicating them. withMessage.Error() prepends w.msg + ": ", which alters fmt.Errorf formatting when %w appears mid-string or alone

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, now I suppose I’ll ask the question: why recreate WithStack(fmt.Errorf(format, args...))?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WithStack(fmt.Errorf(format, args...)) produces a three-layer chain: withStack -> fmt.wrapError -> cause. Callers would need a double Unwrap to reach the cause. More critically, withStack.Format delegates to the inner error's Format method, and fmt.wrapError has no custom Format, so %+v output loses the full stack frame rendering that fundamental.Format provides.

By embedding *fundamental directly, wrapError preserves the exact Error(), Format(), and StackTrace() behavior that Errorf has always returned. The chain stays flat at two levels (wrapError -> cause), and Unwrap returns the cause directly. The only addition is the Unwrap() error method so the wrapped error participates in errors.Is/errors.As.


func (w *wrapError) Cause() error { return w.err }

// Unwrap provides compatibility for Go 1.13 error chains.
func (w *wrapError) Unwrap() error { return w.err }

type wrapErrors struct {
*fundamental
errs []error

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why recreate &withMessage{ cause: errors.Join( &fundamental { … }, … ) }?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in eae2cc5: wrapErrors now embeds *fundamental as well. errors.Join requires Go 1.20+ (this package targets Go 1.13+) and joins messages with newlines rather than preserving fmt.Errorf formatting

}

func (w *wrapErrors) Cause() error {
if len(w.errs) > 0 {
return w.errs[0]
}
return nil
}

// Unwrap provides compatibility for Go 1.20 error chains.
func (w *wrapErrors) Unwrap() []error { return w.errs }

// fundamental is an error that has a message and a stack, but no caller.
type fundamental struct {
msg string
Expand Down
146 changes: 146 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"reflect"
"strings"
"testing"
)

Expand Down Expand Up @@ -139,6 +140,10 @@ func TestErrorf(t *testing.T) {
}{
{Errorf("read error without format specifiers"), "read error without format specifiers"},
{Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"},
{Errorf("read error: %w", io.EOF), "read error: EOF"},
{Errorf("%w: client error", io.EOF), "EOF: client error"},
{Errorf("read %d bytes error: %w", 42, io.EOF), "read 42 bytes error: EOF"},
{Errorf("%w", io.EOF), "EOF"},
}

for _, tt := range tests {
Expand All @@ -149,6 +154,147 @@ func TestErrorf(t *testing.T) {
}
}

func TestErrorfWrapping(t *testing.T) {
base := errors.New("base error")
wrapped := Errorf("wrapped: %w", base)

// Verify Unwrap() error
u, ok := wrapped.(interface{ Unwrap() error })
if !ok {
t.Fatal("expected wrapped error to implement Unwrap() error")
}
if got := u.Unwrap(); got != base {
t.Errorf("Unwrap() = %v, want %v", got, base)
}

// Verify Cause() error
c, ok := wrapped.(interface{ Cause() error })
if !ok {
t.Fatal("expected wrapped error to implement Cause() error")
}
if got := c.Cause(); got != base {
t.Errorf("Cause() = %v, want %v", got, base)
}
if got := Cause(wrapped); got != base {
t.Errorf("Cause(wrapped) = %v, want %v", got, base)
}

// Verify nested Cause and Unwrap chains
outer := Errorf("outer: %w", wrapped)
uOuter, ok := outer.(interface{ Unwrap() error })
if !ok {
t.Fatal("expected outer error to implement Unwrap() error")
}
if got := uOuter.Unwrap(); got != wrapped {
t.Errorf("outer.Unwrap() = %v, want %v", got, wrapped)
}
if got := Cause(outer); got != base {
t.Errorf("Cause(outer) = %v, want %v", got, base)
}

// Verify non-%w does not implement Unwrap() error
plain := Errorf("plain %s", "error")
if _, ok := plain.(interface{ Unwrap() error }); ok {
t.Errorf("Errorf without %%w should not implement Unwrap() error")
}

// Verify %w with nil error operand returns fundamental (no Unwrap)
var nilErr error
wrapNil := Errorf("wrap nil: %w", nilErr)
if _, ok := wrapNil.(interface{ Unwrap() error }); ok {
t.Errorf("wrapNil should not implement Unwrap() error")
}
if _, ok := wrapNil.(*fundamental); !ok {
t.Errorf("wrapNil type = %T, want *fundamental", wrapNil)
}
if got := Cause(wrapNil); got != wrapNil {
t.Errorf("Cause(wrapNil) = %v, want %v", got, wrapNil)
}

// Verify StackTrace
st, ok := wrapped.(interface{ StackTrace() StackTrace })
if !ok {
t.Fatal("expected wrapped error to implement StackTrace()")
}
if len(st.StackTrace()) == 0 {
t.Error("expected non-empty stack trace")
}

// Verify formatting verbs
if got := fmt.Sprintf("%s", wrapped); got != "wrapped: base error" {
t.Errorf("%%s format = %q, want %q", got, "wrapped: base error")
}
if got := fmt.Sprintf("%v", wrapped); got != "wrapped: base error" {
t.Errorf("%%v format = %q, want %q", got, "wrapped: base error")
}
if got := fmt.Sprintf("%q", wrapped); got != `"wrapped: base error"` {
t.Errorf("%%q format = %q, want %q", got, `"wrapped: base error"`)
}
plusV := fmt.Sprintf("%+v", wrapped)
if !strings.Contains(plusV, "wrapped: base error") || !strings.Contains(plusV, "TestErrorfWrapping") {
t.Errorf("%%+v format missing expected message or stack: %q", plusV)
}
}

func TestErrorfMultiWrap(t *testing.T) {
err1 := errors.New("err1")
err2 := errors.New("err2")
multi := Errorf("first: %w, second: %w", err1, err2)

u, ok := multi.(interface{ Unwrap() []error })
if !ok {
t.Fatal("expected multi-wrapped error to implement Unwrap() []error")
}
errs := u.Unwrap()
if len(errs) != 2 || errs[0] != err1 || errs[1] != err2 {
t.Errorf("multi.Unwrap() = %v, want [%v, %v]", errs, err1, err2)
}
if got := Cause(multi); got != err1 {
t.Errorf("Cause(multi) = %v, want %v", got, err1)
}
if got := multi.Error(); got != "first: err1, second: err2" {
t.Errorf("multi.Error() = %q, want %q", got, "first: err1, second: err2")
}
if st, ok := multi.(interface{ StackTrace() StackTrace }); !ok || len(st.StackTrace()) == 0 {
t.Errorf("expected multi-wrapped error to have non-empty StackTrace")
}
if got := fmt.Sprintf("%q", multi); got != `"first: err1, second: err2"` {
t.Errorf("%%q format = %q, want %q", got, `"first: err1, second: err2"`)
}
plusV := fmt.Sprintf("%+v", multi)
if !strings.Contains(plusV, "first: err1, second: err2") || !strings.Contains(plusV, "TestErrorfMultiWrap") {
t.Errorf("%%+v format missing expected message or stack: %q", plusV)
}

// Verify 1-len []error unwraps as wrapError (Unwrap() error)
var nilErr error
singleFromMulti := Errorf("first: %w, second: %w", err1, nilErr)
if _, ok := singleFromMulti.(*wrapError); !ok {
t.Errorf("singleFromMulti type = %T, want *wrapError", singleFromMulti)
}
if uSingle, ok := singleFromMulti.(interface{ Unwrap() error }); !ok || uSingle.Unwrap() != err1 {
t.Errorf("singleFromMulti.Unwrap() = %v, want %v", uSingle, err1)
}
if got := Cause(singleFromMulti); got != err1 {
t.Errorf("Cause(singleFromMulti) = %v, want %v", got, err1)
}

// Verify 0-len []error returns fundamental (no Unwrap)
zeroFromMulti := Errorf("first: %w, second: %w", nilErr, nilErr)
if _, ok := zeroFromMulti.(*fundamental); !ok {
t.Errorf("zeroFromMulti type = %T, want *fundamental", zeroFromMulti)
}
if _, ok := zeroFromMulti.(interface{ Unwrap() error }); ok {
t.Errorf("zeroFromMulti should not implement Unwrap() error")
}
if _, ok := zeroFromMulti.(interface{ Unwrap() []error }); ok {
t.Errorf("zeroFromMulti should not implement Unwrap() []error")
}
if got := Cause(zeroFromMulti); got != zeroFromMulti {
t.Errorf("Cause(zeroFromMulti) = %v, want %v", got, zeroFromMulti)
}
}

func TestWithStackNil(t *testing.T) {
got := WithStack(nil)
if got != nil {
Expand Down
21 changes: 21 additions & 0 deletions go113_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ func TestIs(t *testing.T) {
},
want: true,
},
{
name: "errorf with %w",
args: args{
err: Errorf("wrap it: %w", err),
target: err,
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -121,6 +129,14 @@ func TestAs(t *testing.T) {
},
want: true,
},
{
name: "errorf with %w",
args: args{
err: Errorf("wrap it: %w", err),
target: new(customErr),
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -167,6 +183,11 @@ func TestUnwrap(t *testing.T) {
args: args{err: fmt.Errorf("wrap: %w", err)},
want: err,
},
{
name: "errorf with %w",
args: args{err: Errorf("wrap: %w", err)},
want: err,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down