Skip to content

Commit

Permalink
fix: custom error type in handler when return nil (issue #5 ; pr #6)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexisvisco authored Jul 5, 2021
1 parent c5f22f3 commit 8be2cf6
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 5 deletions.
14 changes: 11 additions & 3 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,12 @@ func Handler(h interface{}, defaultStatusCode int) http.HandlerFunc {
}
}

var err, outputStruct interface{}
var (
outputStruct interface{}
err interface{}
)

err = nil

// funcIn contains the input parameters of the kcd handler call.
var args []reflect.Value
Expand All @@ -131,10 +136,13 @@ func Handler(h interface{}, defaultStatusCode int) http.HandlerFunc {
ret := hv.Call(args)

if !isStdHTTPHandler {
errIndex := 0
if outType != nil {
outputStruct = ret[0].Interface()
err = ret[1].Interface()
} else {
errIndex = 1
}

if !ret[errIndex].IsNil() {
err = ret[0].Interface()
}
}
Expand Down
16 changes: 16 additions & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,21 @@ func std(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("ok"))
}

type ErrImpl struct{}

func (t *ErrImpl) Error() string {
return "aaaa"
}

func testCustomErrNil() *ErrImpl {
return nil
}

func TestBind(t *testing.T) {
r := chi.NewRouter()

r.Get("/hello", kcd.Handler(std, 200))
r.Get("/testerrimpl", kcd.Handler(testCustomErrNil, 200))
r.Post("/{uint}", kcd.Handler(hookBindHandler, 200))

server := httptest.NewServer(r)
Expand All @@ -153,6 +164,11 @@ func TestBind(t *testing.T) {
assert.Equal(t, "ok", body)
})

t.Run("it should return nil with custom error", func(t *testing.T) {
body := e.GET("/testerrimpl").Expect().Body().Raw()
assert.Equal(t, "", body)
})

t.Run("it should succeed", func(t *testing.T) {
expect := e.POST("/4").
WithJSON(hookBindStruct{JSONName: ValString}).
Expand Down
2 changes: 1 addition & 1 deletion internal/decoder/field_setter.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (f fieldSetter) set() error {
func (f fieldSetter) setForArrayOrSlice(ptr bool, list []string) error {
var (
element reflect.Value
array = false
array bool
)

isTypePtr := false
Expand Down
2 changes: 1 addition & 1 deletion pkg/extractor/extractors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ type ExtractorTestStruct struct {

EmbeddedExtractorTest
*EmbeddedPtrExtractorTest
//embeddedQueryExtractor will don't work since it's not accessible
// embeddedQueryExtractor will don't work since it's not accessible

SubStruct SubStructExtractorTest

Expand Down

0 comments on commit 8be2cf6

Please sign in to comment.