Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions api/batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"sync"
"time"

Expand Down Expand Up @@ -79,21 +78,32 @@ func Batch[T any](c *Client, tasks []BatchTask[T], opts ...BatchOption) ([]mo.Re
return results, nil
}

// errorRaw builds a JSON object {"error": "<msg>"} with the message properly
// escaped. Interpolating err.Error() directly produced invalid JSON whenever the
// error string contained quotes (e.g. *url.Error: `Get "http://host": ...`),
// breaking the marshal of the whole batch.
func errorRaw(msg string) *json.RawMessage {
b, err := json.Marshal(map[string]string{"error": msg})
if err != nil {
b = []byte(`{"error": "failed to marshal error message"}`)
}
raw := json.RawMessage(b)
return &raw
}

func BatchResultToRaw(r mo.Result[*Response]) *json.RawMessage {
err := r.Error()
if err != nil {
jsonErr, ok := errors.AsType[*JSONError](err)
if ok {
return &jsonErr.Raw
}
errRaw := json.RawMessage(fmt.Sprintf(`{"error": "%s"}`, err.Error()))
return &errRaw
return errorRaw(err.Error())
}
resp := r.MustGet()
raw, err := resp.ToJSON()
if err != nil {
errRaw := json.RawMessage(fmt.Sprintf(`{"error": "%s"}`, err.Error()))
return &errRaw
return errorRaw(err.Error())
}
return raw
}
15 changes: 15 additions & 0 deletions api/batch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package api

import (
"context"
"encoding/json"
"errors"
"net/http"
"testing"

Expand Down Expand Up @@ -40,3 +42,16 @@ func TestBatch(t *testing.T) {
assert.Equal(t, results[0].MustGet().StatusCode, http.StatusOK)
assert.Equal(t, results[1].MustGet().StatusCode, http.StatusOK)
}

func TestBatchResultToRawEscapesQuotesInError(t *testing.T) {
// *url.Error-style messages contain quotes; they must not break the JSON.
err := errors.New(`Get "http://example.com/": context deadline exceeded`)
raw := BatchResultToRaw(mo.Err[*Response](err))

_, jsonErr := json.Marshal(raw)
assert.NoError(t, jsonErr)

var obj map[string]string
assert.NoError(t, json.Unmarshal(*raw, &obj))
assert.Equal(t, err.Error(), obj["error"])
}