Skip to content

Commit

Permalink
Merge pull request #23 from mailgun/sergey/WithContext
Browse files Browse the repository at this point in the history
WithContext Wrap and Wrapf should return nil if wrapped err is nil
  • Loading branch information
thrawn01 authored Jun 21, 2018
2 parents 49b8883 + 58a91f2 commit f0b7012
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
12 changes: 12 additions & 0 deletions errors/with_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
11 changes: 11 additions & 0 deletions errors/with_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}

0 comments on commit f0b7012

Please sign in to comment.