forked from simplesurance/bunny-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
96 lines (79 loc) · 2.34 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package bunny
import (
"fmt"
"net/http"
"strings"
)
// HTTPError is returned by the Client when an unsuccessful HTTP response was
// returned or a response could not be processed.
// If the body of an unsuccessful HTTP response contains an APIError in the
// body, APIError is returned by the Client instead.
type HTTPError struct {
// RequestURL is the address to which the request was sent that caused the error.
RequestURL string
// The HTTP response status code.
StatusCode int
// The raw http response body. It's nil if the response had no body or it could not be received.
RespBody []byte
// Errors contain errors that happened while receiving or processing the HTTP response.
Errors []error
}
// Error returns a textual representation of the error.
func (e *HTTPError) Error() string {
var res strings.Builder
res.WriteString(fmt.Sprintf("http-request to %s failed: %s (%d)",
e.RequestURL, http.StatusText(e.StatusCode), e.StatusCode,
))
if len(e.Errors) > 0 {
res.WriteString(", errors: " + strings.Join(errorsToStrings(e.Errors), ", "))
}
return res.String()
}
func errorsToStrings(errs []error) []string {
res := make([]string, 0, len(errs))
for _, err := range errs {
res = append(res, err.Error())
}
return res
}
// AuthenticationError represents an Unauthorized (401) HTTP error.
type AuthenticationError struct {
Message string
}
// Error returns a textual representation of the error.
func (e *AuthenticationError) Error() string {
return e.Message
}
// APIError represents an error that is returned by some Bunny API endpoints on
// failures.
type APIError struct {
HTTPError
ErrorKey string `json:"ErrorKey"`
Field string `json:"Field"`
Message string `json:"Message"`
}
// Error returns the string representation of the error.
// ErrorKey, Field and Message are omitted if they are empty.
func (e *APIError) Error() string {
var res strings.Builder
res.WriteString(e.HTTPError.Error())
if e.ErrorKey != "" {
res.WriteString(", ")
res.WriteString(e.ErrorKey)
if e.Field != "" {
res.WriteString(": ")
res.WriteString(e.Field)
}
} else {
if e.Field != "" {
res.WriteString(", ")
res.WriteString(e.Field)
}
}
if e.Message != "" {
// Field and ErrorKey contains the same information then Message, no need to log them.
res.WriteString(", ")
res.WriteString(e.Message)
}
return res.String()
}