fix(client): handle error responses with detailed messages #287
@@ -69,6 +69,12 @@ func (r *RestClient) projectApiCall(method, project string, api string, body io.
|
||||
if resp.StatusCode == http.StatusOK && response != nil {
|
||||
decoder := json.NewDecoder(resp.Body)
|
||||
err = decoder.Decode(response)
|
||||
} else if resp.StatusCode != http.StatusOK {
|
||||
buff, err2 := io.ReadAll(resp.Body)
|
||||
if err2 != nil {
|
||||
return fmt.Errorf("error reading body: %w", err2)
|
||||
}
|
||||
return fmt.Errorf("status %d: %s", resp.StatusCode, string(buff))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -80,6 +80,39 @@ func TestRestClient_GetTags(t *testing.T) {
|
||||
return assert.EqualError(t, err, "invalid character 'a' looking for beginning of value")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unauthorized",
|
||||
args: args{
|
||||
project: "unboundsoftware/dummy",
|
||||
},
|
||||
handler: func(t *testing.T) http.HandlerFunc {
|
||||
return func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = writer.Write([]byte("token expired"))
|
||||
}
|
||||
},
|
||||
want: nil,
|
||||
wantErr: func(t assert.TestingT, err error, i ...interface{}) bool {
|
||||
return assert.EqualError(t, err, "status 401: token expired")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "error body length incorrect",
|
||||
args: args{
|
||||
project: "unboundsoftware/dummy",
|
||||
},
|
||||
handler: func(t *testing.T) http.HandlerFunc {
|
||||
return func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.Header().Set("Content-Length", "230")
|
||||
writer.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = writer.Write([]byte("token expired"))
|
||||
}
|
||||
},
|
||||
want: nil,
|
||||
wantErr: func(t assert.TestingT, err error, i ...interface{}) bool {
|
||||
return assert.EqualError(t, err, "error reading body: unexpected EOF")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "success",
|
||||
args: args{
|
||||
|
||||
Reference in New Issue
Block a user