From 97c51d80fd026f75af498f2a7f51686c2e94dbf1 Mon Sep 17 00:00:00 2001 From: "Derrick J. Wippler" Date: Mon, 17 Apr 2023 14:04:32 -0400 Subject: [PATCH] Added errors.Errorf() (#5) --- errors.go | 13 +++++++++++++ errors_test.go | 3 +-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/errors.go b/errors.go index 1f2aae0..c55116b 100644 --- a/errors.go +++ b/errors.go @@ -2,6 +2,7 @@ package errors import ( "errors" + "fmt" "reflect" ) @@ -35,6 +36,18 @@ func Unwrap(err error) error { return errors.Unwrap(err) } +// Errorf formats according to a format specifier and returns the string as a +// value that satisfies error. +// +// If the format specifier includes a %w verb with an error operand, +// the returned error will implement an Unwrap method returning the operand. It is +// invalid to include more than one %w verb or to supply it with an operand +// that does not implement the error interface. The %w verb is otherwise +// a synonym for %v. +func Errorf(format string, a ...any) error { + return fmt.Errorf(format, a...) +} + // Last finds the last error in err's chain that matches target, and if one is found, sets // target to that error value and returns true. Otherwise, it returns false. // diff --git a/errors_test.go b/errors_test.go index 5d1bbe1..7da4dcd 100644 --- a/errors_test.go +++ b/errors_test.go @@ -1,7 +1,6 @@ package errors_test import ( - "fmt" "testing" "github.com/mailgun/errors" @@ -45,7 +44,7 @@ func TestLast(t *testing.T) { err = errors.Wrap(err, "last") err = errors.Wrap(err, "second") err = errors.Wrap(err, "first") - err = fmt.Errorf("wrapped: %w", err) + err = errors.Errorf("wrapped: %w", err) // errors.As() returns the "first" error in the chain with a stack trace var first callstack.HasStackTrace