1
0
mirror of synced 2024-11-25 06:26:03 +03:00

fix review

This commit is contained in:
Ruslan Efanov 2022-10-26 14:58:32 +03:00
parent bf7e5cdb93
commit 8765026f7e
5 changed files with 25 additions and 15 deletions

View File

@ -742,10 +742,10 @@ func (t *MGClientTest) Test_SuccessHandleError() {
t.Assert().Equal(http.StatusInternalServerError, statusCode)
t.Assert().IsType(new(httpClientError), err)
t.Assert().Equal("Internal server error", err.Error())
t.Assert().Equal(internalServerError, err.Error())
var serverErr *httpClientError
if errors.As(err, &serverErr) {
t.Assert().NotNil(serverErr.ResponseBody)
t.Assert().NotNil(serverErr.LimitedResponse)
} else {
t.Fail("Unexpected type of error")
}

View File

@ -1,6 +1,7 @@
package v1
import (
"bytes"
"encoding/json"
"errors"
"fmt"
@ -8,19 +9,23 @@ import (
"net/http"
)
var defaultErrorMessage = "Internal http client error"
var internalServerError = "Internal server error"
var defaultErrorMessage = "internal http client error"
var internalServerError = "internal server error"
type httpClientError struct {
ErrorMsg string
BaseError error
ResponseBody io.ReadCloser
ErrorMsg string
BaseError error
LimitedResponse io.Reader
}
func (err *httpClientError) Unwrap() error {
return err.BaseError
}
func (err *httpClientError) Is(target error) bool {
return errors.As(target, &err)
}
func (err *httpClientError) Error() string {
message := defaultErrorMessage
@ -59,7 +64,7 @@ func NewAPIClientError(responseBody []byte) error {
func NewServerError(response *http.Response) error {
var data []byte
body, err := buildRawResponse(response)
body, err := buildLimitedRawResponse(response)
if err == nil {
data = body
}
@ -68,7 +73,7 @@ func NewServerError(response *http.Response) error {
var serverError *httpClientError
if errors.As(err, &serverError) {
serverError.ResponseBody = response.Body
serverError.LimitedResponse = bytes.NewBuffer(body)
return serverError
}

View File

@ -47,7 +47,7 @@ func TestNewServerError(t *testing.T) {
var err *httpClientError
if errors.As(serverErr, &err) {
assert.NotNil(t, err.ResponseBody)
assert.NotNil(t, err.LimitedResponse)
} else {
t.Fatal("Unexpected type of error")
}

View File

@ -5,13 +5,18 @@ import (
"net/http"
)
func buildRawResponse(resp *http.Response) ([]byte, error) {
const MB = 1 << 20
const MaxSizeBody = MB * 0.5
func buildLimitedRawResponse(resp *http.Response) ([]byte, error) {
defer resp.Body.Close()
res, err := io.ReadAll(resp.Body)
limitReader := io.LimitReader(resp.Body, MaxSizeBody)
body, err := io.ReadAll(limitReader)
if err != nil {
return res, err
return body, err
}
return res, nil
return body, nil
}

View File

@ -78,7 +78,7 @@ func makeRequest(reqType, url string, buf io.Reader, c *MgClient) ([]byte, int,
return res, resp.StatusCode, err
}
res, err = buildRawResponse(resp)
res, err = buildLimitedRawResponse(resp)
if err != nil {
return res, 0, err
}