Skip to content

Commit 9ffd5f2

Browse files
committed
Process returned JSON error messages, extracting the error message
1 parent edf1403 commit 9ffd5f2

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

http.go

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,30 @@ import (
1111

1212
// sendRequestJSON sends a request to DBHub.io, formatting the returned result as JSON
1313
func sendRequestJSON(queryUrl string, data url.Values, returnStructure interface{}) (err error) {
14+
type JSONError struct {
15+
Msg string `json:"error"`
16+
}
17+
1418
// Send the request
1519
var body io.ReadCloser
1620
body, err = sendRequest(queryUrl, data)
1721
if err != nil {
22+
if body != nil {
23+
defer body.Close()
24+
25+
// If there's useful error info in the returned JSON, return that as the error message
26+
var z JSONError
27+
err = json.NewDecoder(body).Decode(&z)
28+
if err != nil {
29+
return
30+
}
31+
err = fmt.Errorf("%s", z.Msg)
32+
}
1833
return
1934
}
35+
if body != nil {
36+
defer body.Close()
37+
}
2038

2139
// Unmarshall the JSON response into the structure provided by the caller
2240
err = json.NewDecoder(body).Decode(returnStructure)
@@ -43,17 +61,15 @@ func sendRequest(queryUrl string, data url.Values) (body io.ReadCloser, err erro
4361
return
4462
}
4563

64+
// Return the response body, even if an error occured. This lets us return useful error information provided as
65+
// JSON in the body of the message
66+
body = resp.Body
67+
4668
// Basic error handling, based on the status code received from the server
4769
if resp.StatusCode != 200 {
4870
// The returned status code indicates something went wrong
4971
err = fmt.Errorf(resp.Status)
50-
if resp.Body != nil {
51-
defer resp.Body.Close()
52-
}
5372
return
5473
}
55-
56-
// Return the response body
57-
body = resp.Body
5874
return
5975
}

0 commit comments

Comments
 (0)