diff --git a/api/api.go b/api/api.go index e793b33..24c5ded 100644 --- a/api/api.go +++ b/api/api.go @@ -3,7 +3,9 @@ package api import ( "bytes" "encoding/json" + "errors" "fmt" + "io" "net/http" "github.com/bitrise-io/go-utils/v2/log" @@ -70,5 +72,23 @@ func checkEnvVarShareResponse(resp *http.Response) error { if resp.StatusCode >= 200 && resp.StatusCode < 300 { return nil } - return fmt.Errorf("request to %s failed: status code should be 2xx (%d)", resp.Request.URL, resp.StatusCode) + respErr := fmt.Errorf("request to %s failed: status code should be 2xx (%d)", resp.Request.URL, resp.StatusCode) + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return respErr + } + var respBodyJSON map[string]string + err = json.Unmarshal(respBody, &respBodyJSON) + if err != nil { + respErr = errors.New(respErr.Error() + fmt.Sprintf(", response body: %s", string(respBody))) + return respErr + } + clientRespErrMsg, isSet := respBodyJSON["error_msg"] + if !isSet || respBodyJSON["error_msg"] == "" { + respErr = errors.New(respErr.Error() + fmt.Sprintf(", response body: %s", respBodyJSON)) + return respErr + } + respErr = errors.New(respErr.Error() + fmt.Sprintf(", message: %s", clientRespErrMsg)) + + return respErr } diff --git a/api/api_test.go b/api/api_test.go index 1172356..9c17964 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -86,12 +86,16 @@ func TestBitriseClient_ShareEnvVars_FailingRequest(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { serverCalled = true w.WriteHeader(http.StatusBadRequest) + _, err := w.Write([]byte(`{"error_msg":"some error"}`)) + if err != nil { + return + } })) defer server.Close() c := NewBitriseClient(server.URL, buildSlug, apiToken, log.NewLogger()) err := c.ShareEnvVars(envVars) require.Error(t, err) - require.Equal(t, fmt.Sprintf("request to %s/pipeline/workflow_builds/slug/env_vars failed: status code should be 2xx (400)", server.URL), err.Error()) + require.Equal(t, fmt.Sprintf("request to %s/pipeline/workflow_builds/slug/env_vars failed: status code should be 2xx (400), message: some error", server.URL), err.Error()) require.Equal(t, true, serverCalled) }