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

Commit

Permalink
Add WithMessagef function (#118)
Browse files Browse the repository at this point in the history
WithMessagef utility function to accompany WithMessage, similar to
exiting Wrapf function accompanying Wrap.
  • Loading branch information
chemicL authored and davecheney committed Oct 8, 2018
1 parent c059e47 commit e981d1a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
12 changes: 12 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,18 @@ func WithMessage(err error, message string) error {
}
}

// WithMessagef annotates err with the format specifier.
// If err is nil, WithMessagef returns nil.
func WithMessagef(err error, format string, args ...interface{}) error {
if err == nil {
return nil
}
return &withMessage{
cause: err,
msg: fmt.Sprintf(format, args...),
}
}

type withMessage struct {
cause error
msg string
Expand Down
26 changes: 26 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,32 @@ func TestWithMessage(t *testing.T) {
}
}

func TestWithMessagefNil(t *testing.T) {
got := WithMessagef(nil, "no error")
if got != nil {
t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got)
}
}

func TestWithMessagef(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{WithMessagef(io.EOF, "read error without format specifier"), "client error", "client error: read error without format specifier: EOF"},
{WithMessagef(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
}

for _, tt := range tests {
got := WithMessagef(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
}
}
}

// errors.New, etc values are not expected to be compared by value
// but the change in errors#27 made them incomparable. Assert that
// various kinds of errors have a functional equality operator, even
Expand Down

0 comments on commit e981d1a

Please sign in to comment.