diff --git a/errors.go b/errors.go index 161aea25..eb963daa 100644 --- a/errors.go +++ b/errors.go @@ -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 +} + +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 +} + +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 diff --git a/errors_test.go b/errors_test.go index 2089b2f7..f86bd688 100644 --- a/errors_test.go +++ b/errors_test.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "reflect" + "strings" "testing" ) @@ -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 { @@ -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 { diff --git a/go113_test.go b/go113_test.go index 4ea37e61..4b31f85d 100644 --- a/go113_test.go +++ b/go113_test.go @@ -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) { @@ -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) { @@ -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) {