Skip to content

Commit

Permalink
fix APIError to always report errors
Browse files Browse the repository at this point in the history
* add unit-test

Signed-off-by: elv-gilles <gilles.gaillard@eluv.io>
  • Loading branch information
elv-gilles committed May 5, 2022
1 parent 6df43e7 commit 87042d5
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
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())

}

0 comments on commit 87042d5

Please sign in to comment.