-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
57 lines (52 loc) · 1.26 KB
/
utils.go
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
package hop
import (
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"go.hop.io/sdk/types"
)
type errorResponse struct {
Success bool `json:"success"`
Error types.BadRequest `json:"error"`
}
func handleErrors(res *http.Response) error {
b, err := io.ReadAll(res.Body)
if err != nil {
return err
}
var r errorResponse
err = json.Unmarshal(b, &r)
if err != nil {
return types.ServerError("status code " + strconv.Itoa(res.StatusCode) + " (cannot unmarshal from json): " +
string(b))
}
if r.Success {
return errors.New("api response error: error request was marked as success - please report this to " +
"the go-hop github repository")
}
if r.Error.Code == "invalid_auth" {
return types.NotAuthorized(r.Error.Message)
}
if res.StatusCode == 400 {
// As a special case, for 400s return the r.Error object.
return r.Error
}
if res.StatusCode == 404 {
// Infer that this is a not found error.
return types.NotFound{
Code: r.Error.Code,
Message: r.Error.Message,
}
}
if res.StatusCode >= 500 {
// Infer that this is a internal server error.
return types.ServerError(r.Error.Message)
}
return types.UnknownServerError{
StatusCode: res.StatusCode,
Message: r.Error.Message,
Code: r.Error.Code,
}
}