diff --git a/pkg/quickwit/quickwit.go b/pkg/quickwit/quickwit.go index 09249ae..268523b 100644 --- a/pkg/quickwit/quickwit.go +++ b/pkg/quickwit/quickwit.go @@ -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"}, @@ -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 +} diff --git a/pkg/quickwit/quickwit_test.go b/pkg/quickwit/quickwit_test.go new file mode 100644 index 0000000..9479fbf --- /dev/null +++ b/pkg/quickwit/quickwit_test.go @@ -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)))) + }) + } +} \ No newline at end of file