Skip to content

Commit

Permalink
Improves ParseError response when server response is an unknown json
Browse files Browse the repository at this point in the history
Signed-off-by: vatsal <[email protected]>
  • Loading branch information
imvtsl committed Jul 20, 2024
1 parent 35f2513 commit 54c953b
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 9 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
- Fixes wrong response parsing for security get requests ([#572](https://github.com/opensearch-project/opensearch-go/pull/572))
- Fixes opensearchtransport ignores request context cancellation when `retryBackoff` is configured ([#540](https://github.com/opensearch-project/opensearch-go/pull/540))
- Fixes opensearchtransport sleeps unexpectedly after the last retry ([#540](https://github.com/opensearch-project/opensearch-go/pull/540))
- Improves ParseError response when server response is unknown json(update PR# here)

### Security

Expand Down
2 changes: 1 addition & 1 deletion error.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ func ParseError(resp *Response) error {
return parseError(body, &apiError)
}

return fmt.Errorf("%w: %s", ErrUnknownOpensearchError, string(body))
return &StringError{Status: resp.StatusCode, Err: string(body)}
}

func parseError(body []byte, errStruct error) error {
Expand Down
24 changes: 16 additions & 8 deletions error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,22 @@ func TestError(t *testing.T) {
_ = fmt.Sprintf("%s", testError)
})

t.Run("StringErrorUnknownJSON", func(t *testing.T) {
resp := &opensearch.Response{
StatusCode: http.StatusNotFound,
Body: io.NopCloser(
strings.NewReader(`{"_index":"index","_id":"2","matched":false}`),
),
}
assert.True(t, resp.IsError())
err := opensearch.ParseError(resp)
var testError *opensearch.StringError
require.True(t, errors.As(err, &testError))
assert.Equal(t, http.StatusNotFound, testError.Status)
assert.Contains(t, testError.Err, "{\"_index\":\"index\",\"_id\":\"2\",\"matched\":false}")
_ = fmt.Sprintf("%s", testError)
})

t.Run("Error", func(t *testing.T) {
resp := &opensearch.Response{
StatusCode: http.StatusBadRequest,
Expand Down Expand Up @@ -189,14 +205,6 @@ func TestError(t *testing.T) {
},
WantedErrors: []error{opensearch.ErrJSONUnmarshalBody, opensearch.ErrUnknownOpensearchError},
},
{
Name: "unknown json",
Resp: &opensearch.Response{
StatusCode: http.StatusNotFound,
Body: io.NopCloser(strings.NewReader(`{"_index":"index","_id":"2","matched":false}`)),
},
WantedErrors: []error{opensearch.ErrUnknownOpensearchError},
},
{
Name: "io read error",
Resp: &opensearch.Response{
Expand Down

0 comments on commit 54c953b

Please sign in to comment.