-
Notifications
You must be signed in to change notification settings - Fork 8
/
errors.go
74 lines (58 loc) · 1.42 KB
/
errors.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package metadata
import (
"fmt"
"net/http"
"strings"
"github.com/go-resty/resty/v2"
)
// APIError is the error-set returned by the Linode API when presented with an invalid request
type APIError struct {
Errors []APIErrorReason `json:"errors"`
}
func (e APIError) Error() string {
result := make([]string, len(e.Errors))
for i, msg := range e.Errors {
result[i] = msg.Error()
}
return strings.Join(result, "; ")
}
// APIErrorReason is an individual invalid request message returned by the Linode API
type APIErrorReason struct {
Reason string `json:"reason"`
Field string `json:"field"`
}
func (r APIErrorReason) Error() string {
if len(r.Field) == 0 {
return r.Reason
}
return fmt.Sprintf("[%s] %s", r.Field, r.Reason)
}
// Error wraps the LinodeGo error with the relevant http.Response
type Error struct {
Response *http.Response
Code int
Message string
}
func (g Error) Error() string {
return fmt.Sprintf("[%03d] %s", g.Code, g.Message)
}
func coupleAPIErrors(r *resty.Response, err error) (*resty.Response, error) {
if err != nil {
return nil, Error{Message: err.Error()}
}
if r.Error() == nil {
return r, nil
}
apiError, ok := r.Error().(*APIError)
if !ok {
return nil, fmt.Errorf("returned error type is not *APIError")
}
if len(apiError.Errors) == 0 {
return r, nil
}
return nil, &Error{
Code: r.RawResponse.StatusCode,
Message: apiError.Error(),
Response: r.RawResponse,
}
}