From 0a085edca3f732e030f965ced82b399d0e0da35a Mon Sep 17 00:00:00 2001 From: Dariusz Jedrzejczyk Date: Mon, 5 Jun 2017 14:08:24 +0200 Subject: [PATCH] Add WithMessagef function WithMessagef utility function to accompany WithMessage, similar to exiting Wrapf function accompanying Wrap. --- errors.go | 12 ++++++++++++ errors_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/errors.go b/errors.go index 842ee804..bbfdf2c3 100644 --- a/errors.go +++ b/errors.go @@ -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 diff --git a/errors_test.go b/errors_test.go index c4e6eef6..2089b2f7 100644 --- a/errors_test.go +++ b/errors_test.go @@ -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