Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions httperror.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,20 @@ func (he *HTTPError) Error() string {
return fmt.Sprintf("code=%d, message=%v, err=%v", he.Code, msg, he.err.Error())
}

// Is checks if this error is equal to the target error.
func (he *HTTPError) Is(target error) bool {
if he == target {
return true
}
switch t := target.(type) {
case *HTTPError:
return he.Code == t.Code
case *httpError:
return he.Code == t.code
}
return false
}

// Wrap eturns new HTTPError with given errors wrapped inside
func (he HTTPError) Wrap(err error) error {
return &HTTPError{
Expand Down
52 changes: 52 additions & 0 deletions httperror_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,55 @@ func TestNewHTTPError(t *testing.T) {

assert.Equal(t, err2, err)
}

func TestHTTPError_Is(t *testing.T) {
var testCases = []struct {
name string
err *HTTPError
target error
expect bool
}{
{
name: "ok, same instance",
err: &HTTPError{Code: http.StatusNotFound},
target: &HTTPError{Code: http.StatusNotFound},
expect: true,
},
{
name: "ok, different instance, same code",
err: &HTTPError{Code: http.StatusNotFound},
target: &HTTPError{Code: http.StatusNotFound, Message: "different"},
expect: true,
},
{
name: "ok, target is sentinel error",
err: &HTTPError{Code: http.StatusNotFound},
target: ErrNotFound,
expect: true,
},
{
name: "nok, different code",
err: &HTTPError{Code: http.StatusNotFound},
target: &HTTPError{Code: http.StatusInternalServerError},
expect: false,
},
{
name: "nok, target is sentinel error with different code",
err: &HTTPError{Code: http.StatusNotFound},
target: ErrInternalServerError,
expect: false,
},
{
name: "nok, target is different error type",
err: &HTTPError{Code: http.StatusNotFound},
target: errors.New("some error"),
expect: false,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.expect, errors.Is(tc.err, tc.target))
})
}
}
Loading