/
errors.go
261 lines (225 loc) · 6.84 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package provider
import (
"fmt"
"log"
"net/http"
"net/url"
"reflect"
"github.com/stackpath/virtual-kubelet-stackpath/internal/api/workload/workload_models"
"golang.org/x/oauth2"
)
// ErrNotFound is an error interface which denotes whether the opration failed due
// to a the resource not being found.
type ErrNotFound interface {
NotFound() bool
error
}
// InvalidClientSecretError models when a StackPath API OAuth 2 client ID is
// invalid, either due to an invalid format or because the client ID does not
// exist at StackPath.
type InvalidClientIDError struct{}
// NewInvalidClientIDError wraps an existing error as an invalid client ID error.
func NewInvalidClientIDError() *InvalidClientIDError {
return &InvalidClientIDError{}
}
// Error returns a human-readable invalid client ID error message.
func (e *InvalidClientIDError) Error() string {
return "invalid or unknown StackPath client ID"
}
// InvalidClientSecretError models when a StackPath API OAuth 2 client ID is
// correct, but the client secret is incorrect.
type InvalidClientSecretError struct{}
// NewInvalidClientSecretError wraps an existing error as an invalid client
// secret error.
func NewInvalidClientSecretError() *InvalidClientSecretError {
return &InvalidClientSecretError{}
}
// Error returns a human-readable invalid client secret error message.
func (e *InvalidClientSecretError) Error() string {
return "invalid StackPath client secret"
}
// APIError models an error received from the StackPath API.
type APIError struct {
statusCode int
message string
requestID string
fieldViolations []fieldViolation
ErrNotFound
}
// Error satisfies the error interface for APIError.
func (e *APIError) Error() string {
message := fmt.Sprintf(
"a %d error was returned from StackPath: \"%s\"",
e.statusCode,
e.message,
)
if len(e.fieldViolations) > 0 {
message = fmt.Sprintf("%s. The following fields have errors:", message)
for i, violation := range e.fieldViolations {
if i != 0 {
message = fmt.Sprintf("%s,", message)
}
message = fmt.Sprintf("%s %s: %s", message, violation.field, violation.description)
}
}
if e.requestID != "" {
message = fmt.Sprintf("%s (request ID %s)", message, e.requestID)
}
return message
}
func (e *APIError) NotFound() bool {
return e.statusCode == http.StatusNotFound
}
func (e *APIError) Cause() error {
return e
}
// fieldViolation models a StackPath API 400 error field violation in a single
// struct to ease type checking logic when sending errors to the user.
type fieldViolation struct {
description string
field string
}
// HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status.
// See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
//
// This method is adapted from https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/errors.go
// to prevent having to import the entire grpc-gateway package.
func HTTPStatusFromCode(code int32) int {
switch code {
// OK
case 0:
return http.StatusOK
// Canceled
case 1:
return http.StatusRequestTimeout
// Unknown
case 2:
return http.StatusInternalServerError
// InvalidArgument
case 3:
return http.StatusBadRequest
// DeadlineExceeded
case 4:
return http.StatusGatewayTimeout
// NotFound
case 5:
return http.StatusNotFound
// AlreadyExists
case 6:
return http.StatusConflict
// PermissionDenied
case 7:
return http.StatusForbidden
// Unauthenticated
case 16:
return http.StatusUnauthorized
// ResourceExhausted
case 8:
return http.StatusTooManyRequests
// FailedPrecondition
case 9:
// Note, this deliberately doesn't translate to the similarly named '412 Precondition Failed' HTTP response status.
return http.StatusBadRequest
// Aborted
case 10:
return http.StatusConflict
// OutOfRange
case 11:
return http.StatusBadRequest
// Unimplemented
case 12:
return http.StatusNotImplemented
// Internal
case 13:
return http.StatusInternalServerError
// Unavailable
case 14:
return http.StatusServiceUnavailable
// DataLoss
case 15:
return http.StatusInternalServerError
}
return http.StatusInternalServerError
}
// NewStackPathError factories common StackPath error scenarios into their own
// error types, or returns the original error.
func NewStackPathError(err error) error {
switch rootErr := err.(type) {
// Look for errors performing underlying OAuth 2 authentication.
case *url.Error:
switch typedErr := rootErr.Err.(type) {
case *oauth2.RetrieveError:
switch typedErr.Response.StatusCode {
// A 401 Unauthorized error means the client ID was valid, but the
// corresponding secret wasn't.
case 401:
return NewInvalidClientSecretError()
// A 404 Not Found error means the client ID didn't exist.
case 404:
return NewInvalidClientIDError()
}
}
}
// Determine if this is a StackPath API error. StackPath API error messages
// should have at least an HTTP status code and a message.
var statusCode int
var payload interface{}
var fieldViolations []fieldViolation
var message string
var requestID string
// There are a lot of generated API error structs, so inspect them with
// reflection to get the underlying HTTP status code and Payload object.
// Payload objects are easier to work with as each StackPath API service
// has a single Payload struct.
value := reflect.ValueOf(err)
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
for i := 0; i < value.NumField(); i++ {
f := value.Field(i)
switch value.Type().Field(i).Name {
case "_statusCode":
statusCode = int(f.Int())
case "Payload":
if f.Kind() == reflect.Ptr {
f = f.Elem()
}
payload = f.Interface()
}
}
// Look through the payload for things like the error message, StackPath
// request ID, and other error details.
switch status := payload.(type) {
case workload_models.StackpathapiStatus:
statusCode = HTTPStatusFromCode(status.Code)
message = status.Message
for _, d := range status.Details() {
switch detail := d.(type) {
case *workload_models.StackpathRPCRequestInfo:
requestID = detail.RequestID
case *workload_models.StackpathRPCBadRequest:
for _, violation := range detail.FieldViolations {
fieldViolations = append(fieldViolations, fieldViolation{
description: violation.Description,
field: violation.Field,
})
}
default:
log.Printf("Received a %T detail from a StackPath API workload service error: %v", detail, detail)
}
}
}
// This wasn't a StackPath API error if there's no associated error message
// and HTTP status code.
if message == "" || statusCode == 0 {
return err
}
// Log the underlying error in case the user is interested.
log.Printf("Error received from the StackPath API: %s", err)
return &APIError{
statusCode: statusCode,
message: message,
requestID: requestID,
fieldViolations: fieldViolations,
}
}