Skip to content

Commit

Permalink
Merge pull request #431 from ssoroka/better-panics
Browse files Browse the repository at this point in the history
panic with more descriptive messages
  • Loading branch information
danielgtaylor authored May 5, 2024
2 parents e941efc + 4de821f commit 1796483
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
12 changes: 10 additions & 2 deletions huma.go
Original file line number Diff line number Diff line change
Expand Up @@ -1421,7 +1421,11 @@ var reRemoveIDs = regexp.MustCompile(`\{([^}]+)\}`)
// This function can be overridden to provide custom operation IDs.
var GenerateOperationID = func(method, path string, response any) string {
action := method
body, hasBody := deref(reflect.TypeOf(response)).FieldByName("Body")
t := deref(reflect.TypeOf(response))
if t.Kind() != reflect.Struct {
panic("Response type must be a struct")
}
body, hasBody := t.FieldByName("Body")
if hasBody && method == http.MethodGet && deref(body.Type).Kind() == reflect.Slice {
// Special case: GET with a slice response body is a list operation.
action = "list"
Expand All @@ -1443,7 +1447,11 @@ var GenerateOperationID = func(method, path string, response any) string {
// This function can be overridden to provide custom operation summaries.
var GenerateSummary = func(method, path string, response any) string {
action := method
body, hasBody := deref(reflect.TypeOf(response)).FieldByName("Body")
t := deref(reflect.TypeOf(response))
if t.Kind() != reflect.Struct {
panic("Response type must be a struct")
}
body, hasBody := t.FieldByName("Body")
if hasBody && method == http.MethodGet && deref(body.Type).Kind() == reflect.Slice {
// Special case: GET with a slice response body is a list operation.
action = "list"
Expand Down
12 changes: 12 additions & 0 deletions huma_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1904,3 +1904,15 @@ func BenchmarkHandlerFunc(b *testing.B) {
}
})
}

func TestGenerateFuncsPanicWithDescriptiveMessage(t *testing.T) {
var resp *int
assert.PanicsWithValue(t, "Response type must be a struct", func() {
huma.GenerateOperationID("GET", "/foo", resp)
})

assert.PanicsWithValue(t, "Response type must be a struct", func() {
huma.GenerateSummary("GET", "/foo", resp)
})

}

0 comments on commit 1796483

Please sign in to comment.