diff --git a/pkg/errors/sdk_errors.go b/pkg/errors/sdk_errors.go index e039310e24..7a70a2b5df 100644 --- a/pkg/errors/sdk_errors.go +++ b/pkg/errors/sdk_errors.go @@ -5,19 +5,16 @@ package errors import ( "encoding/json" - "errors" "fmt" + "io" "net/http" ) -const err = "error" +const errorKey = "error" var ( - // ErrJSONErrKey indicates response body did not contain erorr message. - errJSONKey = New("response body expected error message json key not found") - - // ErrUnknown indicates that an unknown error was found in the response body. - errUnknown = New("unknown error") + // Failed to read response body. + errRespBody = New("failed to read response body") ) // SDKError is an error type for Mainflux SDK. @@ -79,17 +76,19 @@ func CheckError(resp *http.Response, expectedStatusCodes ...int) SDKError { } } - var content map[string]interface{} - if err := json.NewDecoder(resp.Body).Decode(&content); err != nil { - return NewSDKErrorWithStatus(err, resp.StatusCode) + body, err := io.ReadAll(resp.Body) + if err != nil { + return NewSDKErrorWithStatus(Wrap(errRespBody, err), resp.StatusCode) } + var content map[string]interface{} + _ = json.Unmarshal(body, &content) - if msg, ok := content[err]; ok { + if msg, ok := content[errorKey]; ok { if v, ok := msg.(string); ok { - return NewSDKErrorWithStatus(errors.New(v), resp.StatusCode) + return NewSDKErrorWithStatus(New(v), resp.StatusCode) } - return NewSDKErrorWithStatus(errUnknown, resp.StatusCode) + return NewSDKErrorWithStatus(fmt.Errorf("%v", msg), resp.StatusCode) } - return NewSDKErrorWithStatus(errJSONKey, resp.StatusCode) + return NewSDKErrorWithStatus(New(string(body)), resp.StatusCode) } diff --git a/pkg/sdk/go/message_test.go b/pkg/sdk/go/message_test.go index 3111f6f077..4a93487ff9 100644 --- a/pkg/sdk/go/message_test.go +++ b/pkg/sdk/go/message_test.go @@ -19,8 +19,6 @@ import ( "github.com/stretchr/testify/assert" ) -const eof = "EOF" - func newMessageService(cc policies.AuthServiceClient) adapter.Service { pub := mocks.NewPublisher() @@ -72,7 +70,7 @@ func TestSendMessage(t *testing.T) { chanID: chanID, msg: msg, auth: invalidToken, - err: errors.NewSDKErrorWithStatus(errors.New(eof), http.StatusUnauthorized), + err: errors.NewSDKErrorWithStatus(errors.New(""), http.StatusUnauthorized), }, "publish message with wrong content type": { chanID: chanID, @@ -90,7 +88,7 @@ func TestSendMessage(t *testing.T) { chanID: chanID, msg: msg, auth: "invalid-token", - err: errors.NewSDKErrorWithStatus(errors.New(eof), http.StatusUnauthorized), + err: errors.NewSDKErrorWithStatus(errors.New(""), http.StatusUnauthorized), }, } for desc, tc := range cases {