Ver Fonte

Add WithMessagef function (#118)

WithMessagef utility function to accompany WithMessage, similar to
exiting Wrapf function accompanying Wrap.
Dariusz Jedrzejczyk há 7 anos atrás
pai
commit
e981d1a2c5
2 ficheiros alterados com 38 adições e 0 exclusões
  1. 12 0
      errors.go
  2. 26 0
      errors_test.go

+ 12 - 0
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

+ 26 - 0
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