-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathresponse.go
More file actions
58 lines (52 loc) · 1.2 KB
/
response.go
File metadata and controls
58 lines (52 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package druid
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
type Response struct {
*http.Response
}
func (r *Response) ExtractError() error {
switch r.StatusCode {
case 200, 201, 202, 204, 304:
return nil
}
errorResponse := &errResponse{Response: r.Response}
data, err := io.ReadAll(r.Body)
if err == nil && data != nil {
errorResponse.Body = data
var raw any
if err := json.Unmarshal(data, &raw); err != nil {
errorResponse.Message = r.Status
} else {
errorResponse.Message = parseError(raw)
}
}
return errorResponse
}
type errResponse struct {
Body []byte
Response *http.Response
Message string
}
func (e *errResponse) Error() string {
path, _ := url.QueryUnescape(e.Response.Request.URL.Path)
return fmt.Sprintf(
"error with code %d %s %s message: %s",
e.Response.StatusCode,
e.Response.Request.Method,
fmt.Sprintf("%s://%s%s", e.Response.Request.URL.Scheme, e.Response.Request.URL.Host, path),
e.Message,
)
}
func parseError(raw any) string {
if raw, isMapSI := raw.(map[string]any); isMapSI {
if errStr, hasErrorStr := raw["error"]; hasErrorStr {
return errStr.(string)
}
}
return fmt.Sprintf("failed to parse unexpected error type: %T", raw)
}