From 46a72cd83e9bcc24cb75b01f2693ae9a25cee736 Mon Sep 17 00:00:00 2001 From: Santi Date: Tue, 26 Apr 2016 23:45:54 +0200 Subject: [PATCH] Add Errorf --- errors.go | 13 +++++++++++++ errors_test.go | 17 +++++++++++++++++ example_test.go | 7 +++++++ 3 files changed, 37 insertions(+) diff --git a/errors.go b/errors.go index f7b18b7..b6b6a85 100644 --- a/errors.go +++ b/errors.go @@ -130,6 +130,19 @@ func (c cause) Error() string { return c.Message() + ": " + c.Cause().Error() func (c cause) Cause() error { return c.cause } func (c cause) Message() string { return c.message } +// Errorf formats according to a format specifier and returns the string +// as a value that satisfies error. +func Errorf(format string, args ...interface{}) error { + pc, _, _, _ := runtime.Caller(1) + return struct { + error + location + }{ + fmt.Errorf(format, args...), + location(pc), + } +} + // Wrap returns an error annotating the cause with message. // If cause is nil, Wrap returns nil. func Wrap(cause error, message string) error { diff --git a/errors_test.go b/errors_test.go index c54bec1..4d0e669 100644 --- a/errors_test.go +++ b/errors_test.go @@ -170,3 +170,20 @@ func TestWrapf(t *testing.T) { } } } + +func TestErrorf(t *testing.T) { + tests := []struct { + err error + want string + }{ + {Errorf("read error without format specifiers"), "read error without format specifiers"}, + {Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"}, + } + + for _, tt := range tests { + got := tt.err.Error() + if got != tt.want { + t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want) + } + } +} diff --git a/example_test.go b/example_test.go index 088d009..c5f2023 100644 --- a/example_test.go +++ b/example_test.go @@ -62,3 +62,10 @@ func ExampleWrapf() { // Output: oh noes #2: whoops } + +func ExampleErrorf() { + err := errors.Errorf("whoops: %s", "foo") + errors.Fprint(os.Stdout, err) + + // Output: github.com/pkg/errors/example_test.go:67: whoops: foo +}