danielgtaylor/huma

Error return for huma.StreamResponse.Body

Closed this issue · 1 comments

Hi everybody. Is this possible to add error return for Body: func(ctx huma.Context) error {?
During streaming might happens everything, and it would be better to have way to return error and properly handle it.

Or it would be better to add ctx huma.Context instead func handler(ctx context.Context, input *MyInput)?

func handler(ctx context.Context, input *MyInput) (*huma.StreamResponse, error) {
	return &huma.StreamResponse{
		Body: func(ctx huma.Context) error { // <- error here please 🙏 
			// Write header info before streaming the body.
			ctx.SetHeader("Content-Type", "text/my-stream")
			writer := ctx.BodyWriter()

			// Update the write deadline to give us extra time.
			if d, ok := writer.(interface{ SetWriteDeadline(time.Time) error }); ok {
				d.SetWriteDeadline(time.Now().Add(5 * time.Second))
			} else {
				fmt.Println("warning: unable to set write deadline")
			}

			// Write the first message, then flush and wait.
			writer.Write([]byte("Hello, I'm streaming!"))
			if f, ok := writer.(http.Flusher); ok {
				f.Flush()
			} else {
				fmt.Println("error: unable to flush")
			}

			time.Sleep(3 * time.Second)

			// Write the second message.
			writer.Write([]byte("Hello, I'm still streaming!"))
                         return nil
		},
	}, nil
}

Thanks!

@quadgod there's no built-in error for streaming because once you write to the stream the HTTP response code and HTTP headers are already sent to the client. You cannot change them anymore, and cannot change what body will be sent (or not sent).

For something like SSE it's best to use a combination of a custom error message the client can parse, and if the error is related to being unable to send data to the client then have the service log or submit metrics so you can investigate.