Skip to content

Commit

Permalink
Merge pull request #280 from danielgtaylor/wrap-write-error
Browse files Browse the repository at this point in the history
fix: return wrapped errors on transform or write failure
  • Loading branch information
danielgtaylor authored Mar 5, 2024
2 parents 279b6f2 + dd90062 commit aa2e3a7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
4 changes: 2 additions & 2 deletions huma.go
Original file line number Diff line number Diff line change
Expand Up @@ -461,12 +461,12 @@ func transformAndWrite(api API, ctx Context, status int, ct string, body any) {
tval, terr := api.Transform(ctx, strconv.Itoa(status), body)
if terr != nil {
ctx.BodyWriter().Write([]byte("error transforming response"))
panic(fmt.Sprintf("error transforming response %+v for %s %s %d: %s\n", tval, ctx.Operation().Method, ctx.Operation().Path, status, terr.Error()))
panic(fmt.Errorf("error transforming response %+v for %s %s %d: %w\n", tval, ctx.Operation().Method, ctx.Operation().Path, status, terr))
}
ctx.SetStatus(status)
if merr := api.Marshal(ctx.BodyWriter(), ct, tval); merr != nil {
ctx.BodyWriter().Write([]byte("error marshaling response"))
panic(fmt.Sprintf("error marshaling response %+v for %s %s %d: %s\n", tval, ctx.Operation().Method, ctx.Operation().Path, status, merr.Error()))
panic(fmt.Errorf("error marshaling response %+v for %s %s %d: %w\n", tval, ctx.Operation().Method, ctx.Operation().Path, status, merr))
}
}

Expand Down
15 changes: 14 additions & 1 deletion huma_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -704,10 +704,23 @@ func TestFeatures(t *testing.T) {
Name: "response-transform-error",
Transformers: []huma.Transformer{
func(ctx huma.Context, status string, v any) (any, error) {
return nil, errors.New("whoops")
return nil, http.ErrNotSupported
},
},
Register: func(t *testing.T, api huma.API) {
api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
called := false
defer func() {
if err := recover(); err != nil {
// Ensure the error is the one we expect, possibly wrapped with
// additional info.
assert.ErrorIs(t, err.(error), http.ErrNotSupported)
}
called = true
}()
next(ctx)
assert.True(t, called)
})
huma.Register(api, huma.Operation{
Method: http.MethodGet,
Path: "/response",
Expand Down

0 comments on commit aa2e3a7

Please sign in to comment.