Skip to content

Commit a16859c

Browse files
committed
add/Is_method
1 parent b1d4430 commit a16859c

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

httperror.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,20 @@ func (he *HTTPError) Error() string {
7373
return fmt.Sprintf("code=%d, message=%v, err=%v", he.Code, msg, he.err.Error())
7474
}
7575

76+
// Is checks if this error is equal to the target error.
77+
func (he *HTTPError) Is(target error) bool {
78+
if he == target {
79+
return true
80+
}
81+
switch t := target.(type) {
82+
case *HTTPError:
83+
return he.Code == t.Code
84+
case *httpError:
85+
return he.Code == t.code
86+
}
87+
return false
88+
}
89+
7690
// Wrap eturns new HTTPError with given errors wrapped inside
7791
func (he HTTPError) Wrap(err error) error {
7892
return &HTTPError{

httperror_test.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,55 @@ func TestNewHTTPError(t *testing.T) {
6565

6666
assert.Equal(t, err2, err)
6767
}
68+
69+
func TestHTTPError_Is(t *testing.T) {
70+
var testCases = []struct {
71+
name string
72+
err *HTTPError
73+
target error
74+
expect bool
75+
}{
76+
{
77+
name: "ok, same instance",
78+
err: &HTTPError{Code: http.StatusNotFound},
79+
target: &HTTPError{Code: http.StatusNotFound},
80+
expect: true,
81+
},
82+
{
83+
name: "ok, different instance, same code",
84+
err: &HTTPError{Code: http.StatusNotFound},
85+
target: &HTTPError{Code: http.StatusNotFound, Message: "different"},
86+
expect: true,
87+
},
88+
{
89+
name: "ok, target is sentinel error",
90+
err: &HTTPError{Code: http.StatusNotFound},
91+
target: ErrNotFound,
92+
expect: true,
93+
},
94+
{
95+
name: "nok, different code",
96+
err: &HTTPError{Code: http.StatusNotFound},
97+
target: &HTTPError{Code: http.StatusInternalServerError},
98+
expect: false,
99+
},
100+
{
101+
name: "nok, target is sentinel error with different code",
102+
err: &HTTPError{Code: http.StatusNotFound},
103+
target: ErrInternalServerError,
104+
expect: false,
105+
},
106+
{
107+
name: "nok, target is different error type",
108+
err: &HTTPError{Code: http.StatusNotFound},
109+
target: errors.New("some error"),
110+
expect: false,
111+
},
112+
}
113+
114+
for _, tc := range testCases {
115+
t.Run(tc.name, func(t *testing.T) {
116+
assert.Equal(t, tc.expect, errors.Is(tc.err, tc.target))
117+
})
118+
}
119+
}

0 commit comments

Comments
 (0)