mirror of
https://github.com/interviewstreet/go-jira.git
synced 2025-02-13 13:48:28 +02:00
Issue 193: only parse application/json content-type as JSON
This commit is contained in:
parent
645898e850
commit
c74da16159
15
error.go
15
error.go
@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
@ -28,12 +29,16 @@ func NewJiraError(resp *Response, httpError error) error {
|
||||
if err != nil {
|
||||
return errors.Wrap(err, httpError.Error())
|
||||
}
|
||||
|
||||
jerr := Error{HTTPError: httpError}
|
||||
err = json.Unmarshal(body, &jerr)
|
||||
if err != nil {
|
||||
httpError = errors.Wrap(errors.New("Could not parse JSON"), httpError.Error())
|
||||
return errors.Wrap(err, httpError.Error())
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
if strings.HasPrefix(contentType, "application/json") {
|
||||
err = json.Unmarshal(body, &jerr)
|
||||
if err != nil {
|
||||
httpError = errors.Wrap(errors.New("Could not parse JSON"), httpError.Error())
|
||||
return errors.Wrap(err, httpError.Error())
|
||||
}
|
||||
} else {
|
||||
return errors.Wrap(httpError, fmt.Sprintf("%s: %s", resp.Status, string(body)))
|
||||
}
|
||||
|
||||
return &jerr
|
||||
|
@ -13,6 +13,7 @@ func TestError_NewJiraError(t *testing.T) {
|
||||
defer teardown()
|
||||
|
||||
testMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"errorMessages":["Issue does not exist or you do not have permission to see it."],"errors":{}}`)
|
||||
})
|
||||
|
||||
@ -47,6 +48,26 @@ func TestError_NoJSON(t *testing.T) {
|
||||
defer teardown()
|
||||
|
||||
testMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `Original message body`)
|
||||
})
|
||||
|
||||
req, _ := testClient.NewRequest("GET", "/", nil)
|
||||
resp, _ := testClient.Do(req, nil)
|
||||
|
||||
err := NewJiraError(resp, errors.New("Original http error"))
|
||||
msg := err.Error()
|
||||
|
||||
if !strings.Contains(msg, "200 OK: Original message body: Original http error") {
|
||||
t.Errorf("Expected the HTTP status: Got\n%s\n", msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestError_BadJSON(t *testing.T) {
|
||||
setup()
|
||||
defer teardown()
|
||||
|
||||
testMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `<html>Not JSON</html>`)
|
||||
})
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user