@@ -11,12 +11,30 @@ import (
11
11
12
12
// sendRequestJSON sends a request to DBHub.io, formatting the returned result as JSON
13
13
func sendRequestJSON (queryUrl string , data url.Values , returnStructure interface {}) (err error ) {
14
+ type JSONError struct {
15
+ Msg string `json:"error"`
16
+ }
17
+
14
18
// Send the request
15
19
var body io.ReadCloser
16
20
body , err = sendRequest (queryUrl , data )
17
21
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
+ }
18
33
return
19
34
}
35
+ if body != nil {
36
+ defer body .Close ()
37
+ }
20
38
21
39
// Unmarshall the JSON response into the structure provided by the caller
22
40
err = json .NewDecoder (body ).Decode (returnStructure )
@@ -43,17 +61,15 @@ func sendRequest(queryUrl string, data url.Values) (body io.ReadCloser, err erro
43
61
return
44
62
}
45
63
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
+
46
68
// Basic error handling, based on the status code received from the server
47
69
if resp .StatusCode != 200 {
48
70
// The returned status code indicates something went wrong
49
71
err = fmt .Errorf (resp .Status )
50
- if resp .Body != nil {
51
- defer resp .Body .Close ()
52
- }
53
72
return
54
73
}
55
-
56
- // Return the response body
57
- body = resp .Body
58
74
return
59
75
}
0 commit comments