Skip to content

Commit b7258d0

Browse files
authored
Merge pull request #1 from fabiante/fix/wrapped-err
Fix error handling of wrapped errors
2 parents fbf34ee + 029187e commit b7258d0

File tree

2 files changed

+45
-4
lines changed

2 files changed

+45
-4
lines changed

error.go

+11-4
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,8 @@ func Error(errM ...*ErrorMap) gin.HandlerFunc {
1515
}
1616

1717
for _, err := range errM {
18-
for _, e := range err.errors {
19-
if e == lastError.Err || errors.Is(e, lastError.Err) {
20-
err.response(c)
21-
}
18+
if err.matchError(lastError.Err) {
19+
err.response(c)
2220
}
2321
}
2422
}
@@ -44,6 +42,15 @@ func (e *ErrorMap) Response(response func(c *gin.Context)) *ErrorMap {
4442
return e
4543
}
4644

45+
func (e *ErrorMap) matchError(actual error) bool {
46+
for _, expected := range e.errors {
47+
if errors.Is(actual, expected) {
48+
return true
49+
}
50+
}
51+
return false
52+
}
53+
4754
func NewErrMap(err ...error) *ErrorMap {
4855
return &ErrorMap{errors: err}
4956
}

error_test.go

+34
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,22 @@ func TestErrToStatusCode(t *testing.T) {
2727
}
2828
}
2929

30+
// TestWrappedErrToStatusCode ensures that the middleware also works with wrapped errors.
31+
func TestWrappedErrToStatusCode(t *testing.T) {
32+
r := gin.Default()
33+
r.Use(Error(NewErrMap(BadRequestErr).StatusCode(http.StatusBadRequest)))
34+
r.GET("/test", func(c *gin.Context) {
35+
_ = c.Error(fmt.Errorf("%w: this is a wrapped error", BadRequestErr))
36+
})
37+
38+
recorder := httptest.NewRecorder()
39+
r.ServeHTTP(recorder, httptest.NewRequest("GET", "/test", nil))
40+
41+
if recorder.Result().StatusCode != http.StatusBadRequest {
42+
t.Errorf("invalid the status code %+v", recorder.Result().StatusCode)
43+
}
44+
}
45+
3046
func TestErrToResponse(t *testing.T) {
3147
r := gin.Default()
3248
r.Use(Error(
@@ -64,3 +80,21 @@ func TestErrToResponse(t *testing.T) {
6480
t.Errorf("invalid the response body %+v", rsp.Error)
6581
}
6682
}
83+
84+
func TestErrorMap_matchError(t *testing.T) {
85+
t.Run("single error", func(t *testing.T) {
86+
em := NewErrMap(BadRequestErr)
87+
err := BadRequestErr
88+
if em.matchError(err) == false {
89+
t.Errorf("error should match")
90+
}
91+
})
92+
93+
t.Run("wrapped error", func(t *testing.T) {
94+
em := NewErrMap(BadRequestErr)
95+
err := fmt.Errorf("%w: Details about this error", BadRequestErr)
96+
if em.matchError(err) == false {
97+
t.Errorf("error should match")
98+
}
99+
})
100+
}

0 commit comments

Comments
 (0)