Skip to content

Commit

Permalink
Merge pull request #19 from martin-helmich/bugfix/process-text-responses
Browse files Browse the repository at this point in the history
Correctly process "text/plain" error responses
  • Loading branch information
jkmw authored Sep 6, 2022
2 parents e6ba3ad + c5a2e74 commit f0c9721
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
21 changes: 21 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,27 @@ func TestCreateZone(t *testing.T) {
assert.Equal(t, "example.de.", created.Name)
}

func TestCreateZoneProducedReadableErrorMessages(t *testing.T) {
c := buildClient(t)

zone := zones.Zone{
Name: "test-error-message.de.",
Type: zones.ZoneTypeZone,
Kind: zones.ZoneKindNative,
Nameservers: []string{"ns1.example.com.", "ns2.example.com."},
}

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

_, err := c.Zones().CreateZone(ctx, "localhost", zone)
require.Nil(t, err, "CreateZone returned error")

_, err2 := c.Zones().CreateZone(ctx, "localhost", zone)
require.Error(t, err2, "CreateZone should return error")
require.Equal(t, "unexpected status code 409: http://localhost:8081/api/v1/servers/localhost/zones Conflict", err2.Error())
}

func TestDeleteZone(t *testing.T) {
c := buildClient(t)

Expand Down
30 changes: 23 additions & 7 deletions pdnshttp/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"strings"
Expand Down Expand Up @@ -88,18 +89,33 @@ func (c *Client) Do(ctx context.Context, req *http.Request, out interface{}) err
if res.StatusCode == http.StatusNotFound {
return ErrNotFound{URL: req.URL.String()}
} else if res.StatusCode >= 400 {
// Get a human readable error message
// from PowerDNS API response
var er ErrResponse
if res.Header.Get("Content-Type") == "application/json" {
// Get a human readable error message
// from PowerDNS API response
var er ErrResponse

if err := json.NewDecoder(res.Body).Decode(&er); err != nil {
return err
}

return ErrUnexpectedStatus{
URL: req.URL.String(),
StatusCode: res.StatusCode,
ErrResponse: er,
}
}

if err := json.NewDecoder(res.Body).Decode(&er); err != nil {
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}

return ErrUnexpectedStatus{
URL: req.URL.String(),
StatusCode: res.StatusCode,
ErrResponse: er,
URL: req.URL.String(),
StatusCode: res.StatusCode,
ErrResponse: ErrResponse{
Message: string(body),
},
}
}

Expand Down

0 comments on commit f0c9721

Please sign in to comment.