From 1025e13cd5362f5d4fbf33633ced460ad3e35e91 Mon Sep 17 00:00:00 2001 From: Charles Kenney Date: Tue, 22 Jun 2021 11:27:48 -0400 Subject: [PATCH] improve generic html error propagation --- errors.go | 5 +++-- errors_test.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/errors.go b/errors.go index 189875d35..234d6f974 100644 --- a/errors.go +++ b/errors.go @@ -63,12 +63,13 @@ func coupleAPIErrors(r *resty.Response, err error) (*resty.Response, error) { if responseContentType != expectedContentType { msg := fmt.Sprintf( - "Unexpected Content-Type: Expected: %v, Received: %v", + "Unexpected Content-Type: Expected: %v, Received: %v\nResponse body: %s", expectedContentType, responseContentType, + string(r.Body()), ) - return nil, NewError(msg) + return nil, Error{Code: r.StatusCode(), Message: msg} } apiError, ok := r.Error().(*APIError) diff --git a/errors_test.go b/errors_test.go index cae7bb3ab..ee379365d 100644 --- a/errors_test.go +++ b/errors_test.go @@ -2,15 +2,58 @@ package linodego import ( "bytes" + "context" "errors" "io/ioutil" "net/http" + "net/http/httptest" "testing" "github.com/go-resty/resty/v2" "github.com/google/go-cmp/cmp" ) +func createTestServer(method, route, contentType, body string, statusCode int) (*httptest.Server, *Client) { + h := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + if r.Method == method && r.URL.Path == route { + rw.Header().Add("Content-Type", contentType) + rw.WriteHeader(statusCode) + rw.Write([]byte(body)) + return + } + rw.WriteHeader(http.StatusNotImplemented) + }) + ts := httptest.NewServer(h) + + client := NewClient(nil) + client.SetBaseURL(ts.URL) + return ts, &client +} + +func TestCoupleAPIErrors_genericHtmlError(t *testing.T) { + rawResponse := ` +500 Internal Server Error + +

500 Internal Server Error

+
nginx
+ +` + route := "/v4/linode/instances/123" + ts, client := createTestServer(http.MethodGet, route, "text/html", rawResponse, http.StatusInternalServerError) + client.SetDebug(true) + defer ts.Close() + + expectedError := Error{ + Code: http.StatusInternalServerError, + Message: "Unexpected Content-Type: Expected: application/json, Received: text/html\nResponse body: " + rawResponse, + } + + _, err := coupleAPIErrors(client.R(context.Background()).SetResult(&Instance{}).Get(ts.URL + route)) + if diff := cmp.Diff(expectedError, err); diff != "" { + t.Errorf("expected error to match but got diff:\n%s", diff) + } +} + func TestCoupleAPIErrors_badGatewayError(t *testing.T) { rawResponse := []byte(` 502 Bad Gateway