Skip to content
Closed
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
17 changes: 17 additions & 0 deletions pkg/quickwit/quickwit.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ func (ds *QuickwitDatasource) CallResource(ctx context.Context, req *backend.Cal
if err != nil {
return err
}
body = normalizeResourceErrorBody(response.StatusCode, body)

responseHeaders := map[string][]string{
"content-type": {"application/json"},
Expand All @@ -266,3 +267,19 @@ func (ds *QuickwitDatasource) CallResource(ctx context.Context, req *backend.Cal
Body: body,
})
}

func normalizeResourceErrorBody(statusCode int, body []byte) []byte {
if statusCode >= http.StatusOK && statusCode < http.StatusMultipleChoices || json.Valid(body) {
return body
}

payload, err := json.Marshal(QuickwitCreationErrorPayload{
Message: strings.TrimSpace(string(body)),
StatusCode: statusCode,
})
if err != nil {
return body
}

return payload
}
42 changes: 42 additions & 0 deletions pkg/quickwit/quickwit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package quickwit

import (
"net/http"
"testing"

"github.com/stretchr/testify/require"
)

func TestNormalizeResourceErrorBody(t *testing.T) {
tests := []struct {
name string
statusCode int
body string
expected string
}{
{
name: "wraps plain text upstream error",
statusCode: http.StatusGatewayTimeout,
body: "upstream request timeout\n",
expected: `{"message":"upstream request timeout","status":504}`,
},
{
name: "preserves JSON error",
statusCode: http.StatusBadGateway,
body: `{"message":"upstream unavailable","status":502}`,
expected: `{"message":"upstream unavailable","status":502}`,
},
{
name: "preserves successful response",
statusCode: http.StatusOK,
body: `{"fields":{}}`,
expected: `{"fields":{}}`,
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
require.Equal(t, test.expected, string(normalizeResourceErrorBody(test.statusCode, []byte(test.body))))
})
}
}
Loading