-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy patherrors.go
567 lines (453 loc) · 14.7 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
package scw
import (
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
"strings"
"time"
"github.com/scaleway/scaleway-sdk-go/errors"
"github.com/scaleway/scaleway-sdk-go/validation"
)
// SdkError is a base interface for all Scaleway SDK errors.
type SdkError interface {
Error() string
IsScwSdkError()
}
// ResponseError is an error type for the Scaleway API
type ResponseError struct {
// Message is a human-friendly error message
Message string `json:"message"`
// Type is a string code that defines the kind of error. This field is only used by instance API
Type string `json:"type,omitempty"`
// Resource is a string code that defines the resource concerned by the error. This field is only used by instance API
Resource string `json:"resource,omitempty"`
// Fields contains detail about validation error. This field is only used by instance API
Fields map[string][]string `json:"fields,omitempty"`
// StatusCode is the HTTP status code received
StatusCode int `json:"-"`
// Status is the HTTP status received
Status string `json:"-"`
RawBody json.RawMessage `json:"-"`
}
func (e *ResponseError) UnmarshalJSON(b []byte) error {
type tmpResponseError ResponseError
tmp := tmpResponseError(*e)
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
}
*e = ResponseError(tmp)
return nil
}
// IsScwSdkError implement SdkError interface
func (e *ResponseError) IsScwSdkError() {}
func (e *ResponseError) Error() string {
s := "scaleway-sdk-go: http error " + e.Status
if e.Resource != "" {
s = fmt.Sprintf("%s: resource %s", s, e.Resource)
}
if e.Message != "" {
s = fmt.Sprintf("%s: %s", s, e.Message)
}
if len(e.Fields) > 0 {
s = fmt.Sprintf("%s: %v", s, e.Fields)
}
return s
}
func (e *ResponseError) GetRawBody() json.RawMessage {
return e.RawBody
}
// hasResponseError returns an SdkError when the HTTP status is not OK.
func hasResponseError(res *http.Response) error {
if res.StatusCode >= 200 && res.StatusCode <= 299 {
return nil
}
newErr := &ResponseError{
StatusCode: res.StatusCode,
Status: res.Status,
}
if res.Body == nil {
return newErr
}
body, err := io.ReadAll(res.Body)
if err != nil {
return errors.Wrap(err, "cannot read error response body")
}
newErr.RawBody = body
// The error content is not encoded in JSON, only returns HTTP data.
contentType := res.Header.Get("Content-Type")
if !strings.HasPrefix(contentType, "application/json") {
newErr.Message = res.Status
return newErr
}
err = json.Unmarshal(body, newErr)
if err != nil {
return errors.Wrap(err, "could not parse error response body")
}
err = unmarshalStandardError(newErr.Type, body)
if err != nil {
return err
}
err = unmarshalNonStandardError(newErr.Type, body)
if err != nil {
return err
}
return newErr
}
func unmarshalStandardError(errorType string, body []byte) error {
var stdErr SdkError
switch errorType {
case "invalid_arguments":
stdErr = &InvalidArgumentsError{RawBody: body}
case "quotas_exceeded":
stdErr = &QuotasExceededError{RawBody: body}
case "transient_state":
stdErr = &TransientStateError{RawBody: body}
case "not_found":
stdErr = &ResourceNotFoundError{RawBody: body}
case "locked":
stdErr = &ResourceLockedError{RawBody: body}
case "permissions_denied":
stdErr = &PermissionsDeniedError{RawBody: body}
case "out_of_stock":
stdErr = &OutOfStockError{RawBody: body}
case "resource_expired":
stdErr = &ResourceExpiredError{RawBody: body}
case "denied_authentication":
stdErr = &DeniedAuthenticationError{RawBody: body}
case "precondition_failed":
stdErr = &PreconditionFailedError{RawBody: body}
default:
return nil
}
err := json.Unmarshal(body, stdErr)
if err != nil {
return errors.Wrap(err, "could not parse error %s response body", errorType)
}
return stdErr
}
func unmarshalNonStandardError(errorType string, body []byte) error {
switch errorType {
// Only in instance API.
case "unknown_resource":
unknownResourceError := &UnknownResource{RawBody: body}
err := json.Unmarshal(body, unknownResourceError)
if err != nil {
return errors.Wrap(err, "could not parse error %s response body", errorType)
}
return unknownResourceError.ToResourceNotFoundError()
case "invalid_request_error":
invalidRequestError := &InvalidRequestError{RawBody: body}
err := json.Unmarshal(body, invalidRequestError)
if err != nil {
return errors.Wrap(err, "could not parse error %s response body", errorType)
}
invalidArgumentsError := invalidRequestError.ToInvalidArgumentsError()
if invalidArgumentsError != nil {
return invalidArgumentsError
}
quotasExceededError := invalidRequestError.ToQuotasExceededError()
if quotasExceededError != nil {
return quotasExceededError
}
// At this point, the invalid_request_error is not an InvalidArgumentsError and
// the default marshalling will be used.
return nil
default:
return nil
}
}
type InvalidArgumentsErrorDetail struct {
ArgumentName string `json:"argument_name"`
Reason string `json:"reason"`
HelpMessage string `json:"help_message"`
}
type InvalidArgumentsError struct {
Details []InvalidArgumentsErrorDetail `json:"details"`
RawBody json.RawMessage `json:"-"`
}
// IsScwSdkError implements the SdkError interface
func (e *InvalidArgumentsError) IsScwSdkError() {}
func (e *InvalidArgumentsError) Error() string {
invalidArgs := make([]string, len(e.Details))
for i, d := range e.Details {
invalidArgs[i] = d.ArgumentName
switch d.Reason {
case "unknown":
invalidArgs[i] += " is invalid for unexpected reason"
case "required":
invalidArgs[i] += " is required"
case "format":
invalidArgs[i] += " is wrongly formatted"
case "constraint":
invalidArgs[i] += " does not respect constraint"
}
if d.HelpMessage != "" {
invalidArgs[i] += ", " + d.HelpMessage
}
}
return "scaleway-sdk-go: invalid argument(s): " + strings.Join(invalidArgs, "; ")
}
func (e *InvalidArgumentsError) GetRawBody() json.RawMessage {
return e.RawBody
}
// UnknownResource is only returned by the instance API.
// Warning: this is not a standard error.
type UnknownResource struct {
Message string `json:"message"`
RawBody json.RawMessage `json:"-"`
}
// ToSdkError returns a standard error InvalidArgumentsError or nil Fields is nil.
func (e *UnknownResource) ToResourceNotFoundError() *ResourceNotFoundError {
resourceNotFound := &ResourceNotFoundError{
RawBody: e.RawBody,
}
messageParts := strings.Split(e.Message, `"`)
// Some errors uses ' and not "
if len(messageParts) == 1 {
messageParts = strings.Split(e.Message, "'")
}
switch len(messageParts) {
case 2: // message like: `"111..." not found`
resourceNotFound.ResourceID = messageParts[0]
case 3: // message like: `Security Group "111..." not found`
resourceNotFound.ResourceID = messageParts[1]
// transform `Security group ` to `security_group`
resourceNotFound.Resource = strings.ReplaceAll(strings.ToLower(strings.TrimSpace(messageParts[0])), " ", "_")
default:
return nil
}
if !validation.IsUUID(resourceNotFound.ResourceID) {
return nil
}
return resourceNotFound
}
// InvalidRequestError is only returned by the instance API.
// Warning: this is not a standard error.
type InvalidRequestError struct {
Message string `json:"message"`
Fields map[string][]string `json:"fields"`
Resource string `json:"resource"`
RawBody json.RawMessage `json:"-"`
}
// ToSdkError returns a standard error InvalidArgumentsError or nil Fields is nil.
func (e *InvalidRequestError) ToInvalidArgumentsError() *InvalidArgumentsError {
// If error has no fields, it is not an InvalidArgumentsError.
if len(e.Fields) == 0 {
return nil
}
invalidArguments := &InvalidArgumentsError{
RawBody: e.RawBody,
}
fieldNames := []string(nil)
for fieldName := range e.Fields {
fieldNames = append(fieldNames, fieldName)
}
sort.Strings(fieldNames)
for _, fieldName := range fieldNames {
for _, message := range e.Fields[fieldName] {
invalidArguments.Details = append(invalidArguments.Details, InvalidArgumentsErrorDetail{
ArgumentName: fieldName,
Reason: "constraint",
HelpMessage: message,
})
}
}
return invalidArguments
}
func (e *InvalidRequestError) ToQuotasExceededError() *QuotasExceededError {
if !strings.Contains(strings.ToLower(e.Message), "quota exceeded for this resource") {
return nil
}
return &QuotasExceededError{
Details: []QuotasExceededErrorDetail{
{
Resource: e.Resource,
Quota: 0,
Current: 0,
},
},
RawBody: e.RawBody,
}
}
type QuotasExceededErrorDetail struct {
Resource string `json:"resource"`
Quota uint32 `json:"quota"`
Current uint32 `json:"current"`
}
type QuotasExceededError struct {
Details []QuotasExceededErrorDetail `json:"details"`
RawBody json.RawMessage `json:"-"`
}
// IsScwSdkError implements the SdkError interface
func (e *QuotasExceededError) IsScwSdkError() {}
func (e *QuotasExceededError) Error() string {
invalidArgs := make([]string, len(e.Details))
for i, d := range e.Details {
invalidArgs[i] = fmt.Sprintf("%s has reached its quota (%d/%d)", d.Resource, d.Current, d.Quota)
}
return "scaleway-sdk-go: quota exceeded(s): " + strings.Join(invalidArgs, "; ")
}
func (e *QuotasExceededError) GetRawBody() json.RawMessage {
return e.RawBody
}
type PermissionsDeniedError struct {
Details []struct {
Resource string `json:"resource"`
Action string `json:"action"`
} `json:"details"`
RawBody json.RawMessage `json:"-"`
}
// IsScwSdkError implements the SdkError interface
func (e *PermissionsDeniedError) IsScwSdkError() {}
func (e *PermissionsDeniedError) Error() string {
invalidArgs := make([]string, len(e.Details))
for i, d := range e.Details {
invalidArgs[i] = fmt.Sprintf("%s %s", d.Action, d.Resource)
}
return "scaleway-sdk-go: insufficient permissions: " + strings.Join(invalidArgs, "; ")
}
func (e *PermissionsDeniedError) GetRawBody() json.RawMessage {
return e.RawBody
}
type TransientStateError struct {
Resource string `json:"resource"`
ResourceID string `json:"resource_id"`
CurrentState string `json:"current_state"`
RawBody json.RawMessage `json:"-"`
}
// IsScwSdkError implements the SdkError interface
func (e *TransientStateError) IsScwSdkError() {}
func (e *TransientStateError) Error() string {
return fmt.Sprintf("scaleway-sdk-go: resource %s with ID %s is in a transient state: %s", e.Resource, e.ResourceID, e.CurrentState)
}
func (e *TransientStateError) GetRawBody() json.RawMessage {
return e.RawBody
}
type ResourceNotFoundError struct {
Resource string `json:"resource"`
ResourceID string `json:"resource_id"`
RawBody json.RawMessage `json:"-"`
}
// IsScwSdkError implements the SdkError interface
func (e *ResourceNotFoundError) IsScwSdkError() {}
func (e *ResourceNotFoundError) Error() string {
return fmt.Sprintf("scaleway-sdk-go: resource %s with ID %s is not found", e.Resource, e.ResourceID)
}
func (e *ResourceNotFoundError) GetRawBody() json.RawMessage {
return e.RawBody
}
type ResourceLockedError struct {
Resource string `json:"resource"`
ResourceID string `json:"resource_id"`
RawBody json.RawMessage `json:"-"`
}
// IsScwSdkError implements the SdkError interface
func (e *ResourceLockedError) IsScwSdkError() {}
func (e *ResourceLockedError) Error() string {
return fmt.Sprintf("scaleway-sdk-go: resource %s with ID %s is locked", e.Resource, e.ResourceID)
}
func (e *ResourceLockedError) GetRawBody() json.RawMessage {
return e.RawBody
}
type OutOfStockError struct {
Resource string `json:"resource"`
RawBody json.RawMessage `json:"-"`
}
// IsScwSdkError implements the SdkError interface
func (e *OutOfStockError) IsScwSdkError() {}
func (e *OutOfStockError) Error() string {
return fmt.Sprintf("scaleway-sdk-go: resource %s is out of stock", e.Resource)
}
func (e *OutOfStockError) GetRawBody() json.RawMessage {
return e.RawBody
}
// InvalidClientOptionError indicates that at least one of client data has been badly provided for the client creation.
type InvalidClientOptionError struct {
errorType string
}
func NewInvalidClientOptionError(format string, a ...interface{}) *InvalidClientOptionError {
return &InvalidClientOptionError{errorType: fmt.Sprintf(format, a...)}
}
// IsScwSdkError implements the SdkError interface
func (e InvalidClientOptionError) IsScwSdkError() {}
func (e InvalidClientOptionError) Error() string {
return "scaleway-sdk-go: " + e.errorType
}
// ConfigFileNotFound indicates that the config file could not be found
type ConfigFileNotFoundError struct {
path string
}
func configFileNotFound(path string) *ConfigFileNotFoundError {
return &ConfigFileNotFoundError{path: path}
}
// ConfigFileNotFoundError implements the SdkError interface
func (e ConfigFileNotFoundError) IsScwSdkError() {}
func (e ConfigFileNotFoundError) Error() string {
return fmt.Sprintf("scaleway-sdk-go: cannot read config file %s: no such file or directory", e.path)
}
// ResourceExpiredError implements the SdkError interface
type ResourceExpiredError struct {
Resource string `json:"resource"`
ResourceID string `json:"resource_id"`
ExpiredSince time.Time `json:"expired_since"`
RawBody json.RawMessage `json:"-"`
}
func (r ResourceExpiredError) Error() string {
return fmt.Sprintf("scaleway-sdk-go: resource %s with ID %s expired since %s", r.Resource, r.ResourceID, r.ExpiredSince.String())
}
func (r ResourceExpiredError) IsScwSdkError() {}
// DeniedAuthenticationError implements the SdkError interface
type DeniedAuthenticationError struct {
Method string `json:"method"`
Reason string `json:"reason"`
RawBody json.RawMessage `json:"-"`
}
func (r DeniedAuthenticationError) Error() string {
var reason string
var method string
switch r.Method {
case "unknown_method":
method = "unknown method"
case "jwt":
method = "JWT"
case "api_key":
method = "API key"
}
switch r.Reason {
case "unknown_reason":
reason = "unknown reason"
case "invalid_argument":
reason = "invalid " + method + " format or empty value"
case "not_found":
reason = method + " does not exist"
case "expired":
reason = method + " is expired"
}
return "scaleway-sdk-go: denied authentication: " + reason
}
func (r DeniedAuthenticationError) IsScwSdkError() {}
// PreconditionFailedError implements the SdkError interface
type PreconditionFailedError struct {
Precondition string `json:"precondition"`
HelpMessage string `json:"help_message"`
RawBody json.RawMessage `json:"-"`
}
func (r PreconditionFailedError) Error() string {
var msg string
switch r.Precondition {
case "unknown_precondition":
msg = "unknown precondition"
case "resource_still_in_use":
msg = "resource is still in use"
case "attribute_must_be_set":
msg = "attribute must be set"
}
if r.HelpMessage != "" {
msg += ", " + r.HelpMessage
}
return "scaleway-sdk-go: precondition failed: " + msg
}
func (r PreconditionFailedError) IsScwSdkError() {}