diff --git a/httperror.go b/httperror.go index 682cce2a0..68eef29b6 100644 --- a/httperror.go +++ b/httperror.go @@ -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{ diff --git a/httperror_test.go b/httperror_test.go index 9ae88abcb..d27ac9b0a 100644 --- a/httperror_test.go +++ b/httperror_test.go @@ -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)) + }) + } +}