Skip to content

Commit

Permalink
Merge pull request pkg#7 from umairidris/wrapf
Browse files Browse the repository at this point in the history
Add Wrapf
  • Loading branch information
davecheney committed Apr 25, 2016
2 parents c86dfce + 9a17912 commit f85d45f
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
14 changes: 14 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,20 @@ func Wrap(cause error, message string) error {
}
}

// Wrapf returns an error annotating the cause with the format specifier.
// If cause is nil, Wrapf returns nil.
func Wrapf(cause error, format string, args ...interface{}) error {
if cause == nil {
return nil
}
pc, _, _, _ := runtime.Caller(1)
return &e{
cause: cause,
message: fmt.Sprintf(format, args...),
loc: loc(pc),
}
}

type causer interface {
Cause() error
}
Expand Down
29 changes: 29 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ func TestFprint(t *testing.T) {
}, {
err: Wrap(Wrap(x, "message"), "another message"),
want: "github.com/pkg/errors/errors_test.go:131: another message\ngithub.com/pkg/errors/errors_test.go:131: message\ngithub.com/pkg/errors/errors_test.go:106: error\n",
}, {
err: Wrapf(x, "message"),
want: "github.com/pkg/errors/errors_test.go:134: message\ngithub.com/pkg/errors/errors_test.go:106: error\n",
}}

for i, tt := range tests {
Expand All @@ -141,3 +144,29 @@ func TestFprint(t *testing.T) {
}
}
}

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

func TestWrapf(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"},
{Wrapf(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 := Wrapf(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
}
}
}
8 changes: 8 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,11 @@ func ExampleFprint() {
// github.com/pkg/errors/example_test.go:34: inner
// github.com/pkg/errors/example_test.go:33: error
}

func ExampleWrapf() {
cause := errors.New("whoops")
err := errors.Wrapf(cause, "oh noes #%d", 2)
fmt.Println(err)

// Output: oh noes #2: whoops
}

0 comments on commit f85d45f

Please sign in to comment.