Skip to content

Commit 14491a2

Browse files
committed
fmt: support %w
When fmt.Errorf is provided with a %w verb with an error operand, return an error implementing an Unwrap method returning that operand. It is invalid to use %w with other formatting functions, to use %w multiple times in a format string, or to use %w with a non-error operand. When the Errorf format string contains an invalid use of %w, the returned error does not implement Unwrap. Change-Id: I534e20d3b163ab22c2b137b1c9095906dc243221 Reviewed-on: https://go-review.googlesource.com/c/go/+/176998 Reviewed-by: Marcel van Lohuizen <[email protected]>
1 parent 3e2c522 commit 14491a2

File tree

4 files changed

+138
-11
lines changed

4 files changed

+138
-11
lines changed

src/fmt/errors.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright 2018 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package fmt
6+
7+
import "errors"
8+
9+
// Errorf formats according to a format specifier and returns the string as a
10+
// value that satisfies error.
11+
//
12+
// If the format specifier includes a %w verb with an error operand,
13+
// the returned error will implement an Unwrap method returning the operand. It is
14+
// invalid to include more than one %w verb or to supply it with an operand
15+
// that does not implement the error innterface. The %w verb is otherwise
16+
// a synonym for %v.
17+
func Errorf(format string, a ...interface{}) error {
18+
p := newPrinter()
19+
p.wrapErrs = true
20+
p.doPrintf(format, a)
21+
s := string(p.buf)
22+
var err error
23+
if p.wrappedErr == nil {
24+
err = errors.New(s)
25+
} else {
26+
err = &wrapError{s, p.wrappedErr}
27+
}
28+
p.free()
29+
return err
30+
}
31+
32+
type wrapError struct {
33+
msg string
34+
err error
35+
}
36+
37+
func (e *wrapError) Error() string {
38+
return e.msg
39+
}
40+
41+
func (e *wrapError) Unwrap() error {
42+
return e.err
43+
}

src/fmt/errors_test.go

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Copyright 2018 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package fmt_test
6+
7+
import (
8+
"errors"
9+
"fmt"
10+
"testing"
11+
)
12+
13+
func TestErrorf(t *testing.T) {
14+
wrapped := errors.New("inner error")
15+
for _, test := range []struct {
16+
err error
17+
wantText string
18+
wantUnwrap error
19+
}{{
20+
err: fmt.Errorf("%w", wrapped),
21+
wantText: "inner error",
22+
wantUnwrap: wrapped,
23+
}, {
24+
err: fmt.Errorf("added context: %w", wrapped),
25+
wantText: "added context: inner error",
26+
wantUnwrap: wrapped,
27+
}, {
28+
err: fmt.Errorf("%w with added context", wrapped),
29+
wantText: "inner error with added context",
30+
wantUnwrap: wrapped,
31+
}, {
32+
err: fmt.Errorf("%s %w %v", "prefix", wrapped, "suffix"),
33+
wantText: "prefix inner error suffix",
34+
wantUnwrap: wrapped,
35+
}, {
36+
err: fmt.Errorf("%[2]s: %[1]w", wrapped, "positional verb"),
37+
wantText: "positional verb: inner error",
38+
wantUnwrap: wrapped,
39+
}, {
40+
err: fmt.Errorf("%v", wrapped),
41+
wantText: "inner error",
42+
}, {
43+
err: fmt.Errorf("added context: %v", wrapped),
44+
wantText: "added context: inner error",
45+
}, {
46+
err: fmt.Errorf("%v with added context", wrapped),
47+
wantText: "inner error with added context",
48+
}, {
49+
err: fmt.Errorf("%w is not an error", "not-an-error"),
50+
wantText: "%!w(string=not-an-error) is not an error",
51+
}, {
52+
err: fmt.Errorf("wrapped two errors: %w %w", errString("1"), errString("2")),
53+
wantText: "wrapped two errors: 1 %!w(fmt_test.errString=2)",
54+
}, {
55+
err: fmt.Errorf("wrapped three errors: %w %w %w", errString("1"), errString("2"), errString("3")),
56+
wantText: "wrapped three errors: 1 %!w(fmt_test.errString=2) %!w(fmt_test.errString=3)",
57+
}, {
58+
err: fmt.Errorf("%w", nil),
59+
wantText: "%!w(<nil>)",
60+
wantUnwrap: nil, // still nil
61+
}} {
62+
if got, want := errors.Unwrap(test.err), test.wantUnwrap; got != want {
63+
t.Errorf("Formatted error: %v\nerrors.Unwrap() = %v, want %v", test.err, got, want)
64+
}
65+
if got, want := test.err.Error(), test.wantText; got != want {
66+
t.Errorf("err.Error() = %q, want %q", got, want)
67+
}
68+
}
69+
}
70+
71+
type errString string
72+
73+
func (e errString) Error() string { return string(e) }

src/fmt/print.go

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
package fmt
66

77
import (
8-
"errors"
98
"internal/fmtsort"
109
"io"
1110
"os"
@@ -123,6 +122,10 @@ type pp struct {
123122
panicking bool
124123
// erroring is set when printing an error string to guard against calling handleMethods.
125124
erroring bool
125+
// wrapErrors is set when the format string may contain a %w verb.
126+
wrapErrs bool
127+
// wrappedErr records the target of the %w verb.
128+
wrappedErr error
126129
}
127130

128131
var ppFree = sync.Pool{
@@ -153,6 +156,7 @@ func (p *pp) free() {
153156
p.buf = p.buf[:0]
154157
p.arg = nil
155158
p.value = reflect.Value{}
159+
p.wrappedErr = nil
156160
ppFree.Put(p)
157161
}
158162

@@ -217,12 +221,6 @@ func Sprintf(format string, a ...interface{}) string {
217221
return s
218222
}
219223

220-
// Errorf formats according to a format specifier and returns the string
221-
// as a value that satisfies error.
222-
func Errorf(format string, a ...interface{}) error {
223-
return errors.New(Sprintf(format, a...))
224-
}
225-
226224
// These routines do not take a format string
227225

228226
// Fprint formats using the default formats for its operands and writes to w.
@@ -576,6 +574,21 @@ func (p *pp) handleMethods(verb rune) (handled bool) {
576574
if p.erroring {
577575
return
578576
}
577+
if verb == 'w' {
578+
// It is invalid to use %w other than with Errorf, more than once,
579+
// or with a non-error arg.
580+
err, ok := p.arg.(error)
581+
if !ok || !p.wrapErrs || p.wrappedErr != nil {
582+
p.wrappedErr = nil
583+
p.wrapErrs = false
584+
p.badVerb(verb)
585+
return true
586+
}
587+
p.wrappedErr = err
588+
// If the arg is a Formatter, pass 'v' as the verb to it.
589+
verb = 'v'
590+
}
591+
579592
// Is it a Formatter?
580593
if formatter, ok := p.arg.(Formatter); ok {
581594
handled = true

src/internal/oserror/errors_test.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,7 @@ func TestIsTimeout(t *testing.T) {
3434
{true, ttError{timeout: true}},
3535
{true, isError{os.ErrTimeout}},
3636
{true, os.ErrTimeout},
37-
// TODO: restore when %w is reimplemented
38-
//{true, fmt.Errorf("wrap: %w", os.ErrTimeout)},
37+
{true, fmt.Errorf("wrap: %w", os.ErrTimeout)},
3938
{false, ttError{timeout: false}},
4039
{false, errors.New("error")},
4140
} {
@@ -53,8 +52,7 @@ func TestIsTemporary(t *testing.T) {
5352
{true, ttError{temporary: true}},
5453
{true, isError{os.ErrTemporary}},
5554
{true, os.ErrTemporary},
56-
// TODO: restore when %w is reimplemented
57-
//{true, fmt.Errorf("wrap: %w", os.ErrTemporary)},
55+
{true, fmt.Errorf("wrap: %w", os.ErrTemporary)},
5856
{false, ttError{temporary: false}},
5957
{false, errors.New("error")},
6058
} {

0 commit comments

Comments
 (0)