Skip to content
This repository was archived by the owner on Dec 1, 2021. It is now read-only.

Commit e981d1a

Browse files
chemicLdavecheney
authored andcommitted
Add WithMessagef function (#118)
WithMessagef utility function to accompany WithMessage, similar to exiting Wrapf function accompanying Wrap.
1 parent c059e47 commit e981d1a

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

errors.go

+12
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,18 @@ func WithMessage(err error, message string) error {
220220
}
221221
}
222222

223+
// WithMessagef annotates err with the format specifier.
224+
// If err is nil, WithMessagef returns nil.
225+
func WithMessagef(err error, format string, args ...interface{}) error {
226+
if err == nil {
227+
return nil
228+
}
229+
return &withMessage{
230+
cause: err,
231+
msg: fmt.Sprintf(format, args...),
232+
}
233+
}
234+
223235
type withMessage struct {
224236
cause error
225237
msg string

errors_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,32 @@ func TestWithMessage(t *testing.T) {
198198
}
199199
}
200200

201+
func TestWithMessagefNil(t *testing.T) {
202+
got := WithMessagef(nil, "no error")
203+
if got != nil {
204+
t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got)
205+
}
206+
}
207+
208+
func TestWithMessagef(t *testing.T) {
209+
tests := []struct {
210+
err error
211+
message string
212+
want string
213+
}{
214+
{io.EOF, "read error", "read error: EOF"},
215+
{WithMessagef(io.EOF, "read error without format specifier"), "client error", "client error: read error without format specifier: EOF"},
216+
{WithMessagef(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
217+
}
218+
219+
for _, tt := range tests {
220+
got := WithMessagef(tt.err, tt.message).Error()
221+
if got != tt.want {
222+
t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
223+
}
224+
}
225+
}
226+
201227
// errors.New, etc values are not expected to be compared by value
202228
// but the change in errors#27 made them incomparable. Assert that
203229
// various kinds of errors have a functional equality operator, even

0 commit comments

Comments
 (0)