diff --git a/errors/with_context.go b/errors/with_context.go index f8c6ba0b..1a2a153b 100644 --- a/errors/with_context.go +++ b/errors/with_context.go @@ -19,7 +19,13 @@ type HasFormat interface { // Creates errors that conform to the `HasContext` interface type WithContext map[string]interface{} +// Wrapf returns an error annotating err with a stack trace +// at the point Wrapf is call, and the format specifier. +// If err is nil, Wrapf returns nil. func (c WithContext) Wrapf(err error, format string, args ...interface{}) error { + if err == nil { + return nil + } return &withContext{ stack: stack.New(1), context: c, @@ -28,7 +34,13 @@ func (c WithContext) Wrapf(err error, format string, args ...interface{}) error } } +// Wrap returns an error annotating err with a stack trace +// at the point Wrap is called, and the supplied message. +// If err is nil, Wrap returns nil. func (c WithContext) Wrap(err error, msg string) error { + if err == nil { + return nil + } return &withContext{ stack: stack.New(1), context: c, diff --git a/errors/with_context_test.go b/errors/with_context_test.go index aa5972f1..daff6f5e 100644 --- a/errors/with_context_test.go +++ b/errors/with_context_test.go @@ -9,6 +9,7 @@ import ( "github.com/mailgun/holster/errors" "github.com/mailgun/holster/stack" . "gopkg.in/check.v1" + "github.com/ahmetb/go-linq" ) type TestError struct { @@ -66,3 +67,13 @@ func (s *WithContextTestSuite) TestWithStack(c *C) { c.Assert(linq.From(files).Contains("with_context_test.go"), Equals, true) c.Assert(linq.From(funcs).Contains("(*WithContextTestSuite).TestWithStack"), Equals, true) } + +func (s *WithContextTestSuite) TestWrapfNil(c *C) { + got := errors.WithContext{"some": "context"}.Wrapf(nil, "no error") + c.Assert(got, IsNil) +} + +func (s *WithContextTestSuite) TestWrapNil(c *C) { + got := errors.WithContext{"some": "context"}.Wrap(nil, "no error") + c.Assert(got, IsNil) +}