Skip to content

Commit

Permalink
Merge pull request #206 from Charliekenney23/better-html-errors
Browse files Browse the repository at this point in the history
improve generic html error propagation
  • Loading branch information
0xch4z authored Jun 22, 2021
2 parents e56ac14 + 1025e13 commit 3e17775
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
5 changes: 3 additions & 2 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
43 changes: 43 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 := `<html>
<head><title>500 Internal Server Error</title></head>
<body bgcolor="white">
<center><h1>500 Internal Server Error</h1></center>
<hr><center>nginx</center>
</body>
</html>`
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(`<html>
<head><title>502 Bad Gateway</title></head>
Expand Down

0 comments on commit 3e17775

Please sign in to comment.