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

Commit 7a0abd8

Browse files
scorredoiradavecheney
authored andcommitted
Add Errorf (#14)
1 parent cd6e0b4 commit 7a0abd8

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

errors.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,19 @@ func (c cause) Error() string { return c.Message() + ": " + c.Cause().Error()
130130
func (c cause) Cause() error { return c.cause }
131131
func (c cause) Message() string { return c.message }
132132

133+
// Errorf formats according to a format specifier and returns the string
134+
// as a value that satisfies error.
135+
func Errorf(format string, args ...interface{}) error {
136+
pc, _, _, _ := runtime.Caller(1)
137+
return struct {
138+
error
139+
location
140+
}{
141+
fmt.Errorf(format, args...),
142+
location(pc),
143+
}
144+
}
145+
133146
// Wrap returns an error annotating the cause with message.
134147
// If cause is nil, Wrap returns nil.
135148
func Wrap(cause error, message string) error {

errors_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,3 +170,20 @@ func TestWrapf(t *testing.T) {
170170
}
171171
}
172172
}
173+
174+
func TestErrorf(t *testing.T) {
175+
tests := []struct {
176+
err error
177+
want string
178+
}{
179+
{Errorf("read error without format specifiers"), "read error without format specifiers"},
180+
{Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"},
181+
}
182+
183+
for _, tt := range tests {
184+
got := tt.err.Error()
185+
if got != tt.want {
186+
t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want)
187+
}
188+
}
189+
}

example_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,10 @@ func ExampleWrapf() {
6262

6363
// Output: oh noes #2: whoops
6464
}
65+
66+
func ExampleErrorf() {
67+
err := errors.Errorf("whoops: %s", "foo")
68+
errors.Fprint(os.Stdout, err)
69+
70+
// Output: github.com/pkg/errors/example_test.go:67: whoops: foo
71+
}

0 commit comments

Comments
 (0)