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

Add Errorf #14

Merged
merged 1 commit into from
Apr 29, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
17 changes: 17 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
7 changes: 7 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}