Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix APIError to always report errors #243

Merged
merged 1 commit into from May 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 11 additions & 7 deletions client_response.go
Expand Up @@ -15,10 +15,9 @@
package runtime

import (
"encoding/json"
"fmt"
"io"

"encoding/json"
)

// A ClientResponse represents a client response
Expand Down Expand Up @@ -61,13 +60,18 @@ type APIError struct {
Code int
}

func (a *APIError) Error() string {
resp, _ := json.Marshal(a.Response)
return fmt.Sprintf("%s (status %d): %s", a.OperationName, a.Code, resp)
func (o *APIError) Error() string {
var resp []byte
if err, ok := o.Response.(error); ok {
resp = []byte("'" + err.Error() + "'")
} else {
resp, _ = json.Marshal(o.Response)
}
return fmt.Sprintf("%s (status %d): %s", o.OperationName, o.Code, resp)
}

func (a *APIError) String() string {
return a.Error()
func (o *APIError) String() string {
return o.Error()
}

// IsSuccess returns true when this elapse o k response returns a 2xx status code
Expand Down
27 changes: 27 additions & 0 deletions client_response_test.go
Expand Up @@ -16,8 +16,11 @@ package runtime

import (
"bytes"
"errors"
"io"
"io/fs"
"io/ioutil"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -61,3 +64,27 @@ func TestResponseReaderFunc(t *testing.T) {
assert.Equal(t, "the header", actual.Header)
assert.Equal(t, 490, actual.Code)
}

func TestResponseReaderFuncError(t *testing.T) {
reader := ClientResponseReaderFunc(func(r ClientResponse, _ Consumer) (interface{}, error) {
_, _ = ioutil.ReadAll(r.Body())
return nil, NewAPIError("fake", errors.New("writer closed"), 490)
})
_, err := reader.ReadResponse(response{}, nil)
assert.NotNil(t, err)
assert.True(t, strings.Contains(err.Error(), "writer closed"), err.Error())

reader = func(r ClientResponse, _ Consumer) (interface{}, error) {
_, _ = ioutil.ReadAll(r.Body())
err := &fs.PathError{
Op: "write",
Path: "path/to/fake",
Err: fs.ErrClosed,
}
return nil, NewAPIError("fake", err, 200)
}
_, err = reader.ReadResponse(response{}, nil)
assert.NotNil(t, err)
assert.True(t, strings.Contains(err.Error(), "file already closed"), err.Error())

}