Skip to content

Commit 2e623c7

Browse files
committed
check error when unmarshalling ExtraBody
1 parent 181c0e8 commit 2e623c7

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

embeddings.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,10 @@ func (c *Client) CreateEmbeddings(
268268

269269
// Deserialize JSON to map[string]any
270270
var body map[string]any
271-
_ = json.Unmarshal(jsonData, &body)
271+
err = json.Unmarshal(jsonData, &body)
272+
if err != nil {
273+
return
274+
}
272275

273276
req, err := c.newRequest(
274277
ctx,

embeddings_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,13 @@ import (
1515
"github.com/sashabaranov/go-openai/internal/test/checks"
1616
)
1717

18+
// badMarshaler produces invalid JSON when marshaled.
19+
type badMarshaler struct{}
20+
21+
func (badMarshaler) MarshalJSON() ([]byte, error) {
22+
return []byte("{"), nil
23+
}
24+
1825
func TestEmbedding(t *testing.T) {
1926
embeddedModels := []openai.EmbeddingModel{
2027
openai.AdaSimilarity,
@@ -325,3 +332,21 @@ func TestDotProduct(t *testing.T) {
325332
t.Errorf("Expected Vector Length Mismatch Error, but got: %v", err)
326333
}
327334
}
335+
336+
// TestCreateEmbeddings_UnmarshalError verifies that an error is returned when
337+
// the JSON bytes produced by marshaling the request cannot be unmarshaled back
338+
// into a map.
339+
func TestCreateEmbeddings_UnmarshalError(t *testing.T) {
340+
client, server, teardown := setupOpenAITestServer()
341+
defer teardown()
342+
343+
server.RegisterHandler("/v1/embeddings", func(w http.ResponseWriter, _ *http.Request) {
344+
w.WriteHeader(http.StatusOK)
345+
fmt.Fprint(w, `{"data":[]}`)
346+
})
347+
348+
_, err := client.CreateEmbeddings(context.Background(), openai.EmbeddingRequest{
349+
Input: badMarshaler{},
350+
})
351+
checks.HasError(t, err, "CreateEmbeddings should fail on unmarshal error")
352+
}

0 commit comments

Comments
 (0)