danielgtaylor / huma

Huma REST/HTTP API Framework for Golang with OpenAPI 3.1
https://huma.rocks/
MIT License
2.16k stars 152 forks source link

Feature request - Ability to write errors to huma.Context during a StreamResponse #574

Open ddl-ebrown opened 2 months ago

ddl-ebrown commented 2 months ago

When implementing a streaming API, there are some instances where processing may fail inside of the Body function, that could be returned as errors.

I understand that making the signature Body: func(ctx huma.Context) (error) instead of Body: func(ctx huma.Context) doesn't make much sense, because once streaming starts returning an error is not possible.

However, before streaming starts it's still possible to return / serialize a JSON error. Doing that requires a bit of boilerplate to set the status header / serialize the response to JSON. I think it would be useful to be able to have helpers that can take a huma.StatusError and write it out to the response through huma.Context. I'm thinking something along the lines of huma.WriteErr, but easier to use. Having access to an api instance in this scenario doesn't feel like the right design / usage.

Thoughts?

danielgtaylor commented 1 month ago

@ddl-ebrown that's a great idea. I do think needing the API instance makes sense though, because content negotiation and marshaling happen from the formats registered with the API instance. Open to ideas how best to implement this.