-
Notifications
You must be signed in to change notification settings - Fork 17
/
error.go
521 lines (437 loc) · 16.6 KB
/
error.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
package easypost
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
// Error represents an Error object returned by the EasyPost API.
//
// These are typically informational about why a request failed (server-side validation issues, missing data, etc.).
//
// This is different from the LibraryError class, which represents exceptions in the EasyPost library, such as bad HTTP status codes or local validation issues.
type Error struct {
// Code is a machine-readable code of the problem encountered.
Code string `json:"code,omitempty" url:"code,omitempty"`
// Errors may be provided if there are multiple errors, for example if
// multiple fields have invalid values.
Errors []*Error `json:"errors,omitempty" url:"errors,omitempty"`
// Field may be provided when the error relates to a specific field.
Field string `json:"field,omitempty" url:"field,omitempty"`
// Message is a human-readable description of the problem encountered.
Message interface{} `json:"message,omitempty" url:"message,omitempty"`
// Suggestion may be provided if the API can provide a suggestion to fix
// the error.
Suggestion string `json:"suggestion,omitempty" url:"suggestion,omitempty"`
}
func (e *Error) UnmarshalJSON(data []byte) error {
type alias Error
tmpError := &struct {
Message interface{} `json:"message,omitempty" url:"message,omitempty"`
*alias
}{
alias: (*alias)(e),
}
if err := json.Unmarshal(data, &tmpError); err != nil {
return err
}
// convert message to string
messages := collectMessages(tmpError.Message, []string{})
e.Message = strings.Join(messages, ", ")
return nil
}
// Recursively traverses a JSON element to extract error messages and returns them as a comma-separated string.
func collectMessages(data interface{}, messages []string) []string {
switch data := data.(type) {
case []interface{}: // ["message", 123] or [{"key": "message"}, {"key": "message"}] or [ ["message", "message"], ["message", "message"] ]
for _, value := range data {
messages = collectMessages(value, messages)
}
case map[string]interface{}: // {"message": "value"} or {"message": ["value1", "value2"]} or {"message": [{"key": "value"}, {"key": "value"}]
for _, value := range data {
messages = collectMessages(value, messages)
}
default:
messages = append(messages, fmt.Sprint(data))
}
return messages
}
// Error provides a pretty printed string of an Error object based on present data.
func (e *Error) Error() string {
if e.Message != "" {
if e.Code != "" {
return e.Code + " " + e.Message.(string)
}
return e.Message.(string)
}
return e.Code
}
// LibraryError is the base type for all errors/exceptions in this EasyPost library.
type LibraryError struct {
// Message is a human-readable error description.
Message string
}
// Error provides a pretty printed string of a LibraryError object.
func (e *LibraryError) Error() string {
return e.Message
}
// Local error types
// LocalError represents an error caused by the EasyPost library itself, such as validation or JSON serialization issues.
type LocalError struct {
LibraryError // subtype of LibraryError
}
// Unwrap returns the underlying LibraryError error.
func (e *LocalError) Unwrap() error {
return &e.LibraryError
}
// EndOfPaginationErrorType is raised when there are no more pages to retrieve.
// TODO: This type will be renamed to EndOfPaginationError in a future release to match the other error types once the EndOfPaginationError helper is removed.
type EndOfPaginationErrorType struct {
LocalError // subtype of LocalError
}
// Unwrap returns the underlying LocalError error.
func (e *EndOfPaginationErrorType) Unwrap() error {
return &e.LocalError
}
// newEndOfPaginationError returns a new EndOfPaginationErrorType object.
func newEndOfPaginationError() *EndOfPaginationErrorType {
return &EndOfPaginationErrorType{LocalError{LibraryError{Message: NoPagesLeftToRetrieve}}}
}
// EndOfPaginationError is a singleton instance of EndOfPaginationErrorType.
// Deprecated: This helper will be removed in a future release. For access to the underlying message, use easypost.NoPagesLeftToRetrieve instead.
var EndOfPaginationError = newEndOfPaginationError()
// FilteringError is raised when there is an issue while running a filtering operation.
type FilteringError struct {
LocalError // subtype of LocalError
}
// Unwrap returns the underlying LocalError error.
func (e *FilteringError) Unwrap() error {
return &e.LocalError
}
// newFilteringError returns a new FilteringError object with the given message.
func newFilteringError(message string) *FilteringError {
return &FilteringError{LocalError{LibraryError{Message: message}}}
}
// InvalidObjectError is raised when an object is invalid.
type InvalidObjectError struct {
LocalError // subtype of LocalError
}
// Unwrap returns the underlying LocalError error.
func (e *InvalidObjectError) Unwrap() error {
return &e.LocalError
}
// newInvalidObjectError returns a new InvalidObjectError object with the given message.
func newInvalidObjectError(message string) *InvalidObjectError {
return &InvalidObjectError{LocalError{LibraryError{Message: message}}}
}
// MissingPropertyError is raised when a required property is missing.
type MissingPropertyError struct {
LocalError // subtype of LocalError
}
// Unwrap returns the underlying LocalError error.
func (e *MissingPropertyError) Unwrap() error {
return &e.LocalError
}
// newMissingPropertyError returns a new MissingPropertyError object with the given property.
func newMissingPropertyError(property string) *MissingPropertyError {
message := MissingProperty + property
return &MissingPropertyError{LocalError{LibraryError{Message: message}}}
}
// MissingWebhookSignatureErrorType is raised when a webhook does not contain a valid HMAC signature.
// TODO: This type will be renamed to MissingWebhookSignatureError in a future release to match the other error types once the MissingWebhookSignatureError helper is removed.
type MissingWebhookSignatureErrorType struct {
LocalError // subtype of LocalError
}
// Unwrap returns the underlying LocalError error.
func (e *MissingWebhookSignatureErrorType) Unwrap() error {
return &e.LocalError
}
// newMissingWebhookSignatureError returns a new MissingWebhookSignatureErrorType object.
func newMissingWebhookSignatureError() *MissingWebhookSignatureErrorType {
return &MissingWebhookSignatureErrorType{LocalError{LibraryError{Message: MissingWebhookSignature}}}
}
// MissingWebhookSignatureError is raised when a webhook does not contain a valid HMAC signature.
// Deprecated: This helper will be removed in a future release. For access to the underlying message, use easypost.MissingWebhookSignature instead.
var MissingWebhookSignatureError = newMissingWebhookSignatureError()
// MismatchWebhookSignatureErrorType is raised when a webhook received did not originate from EasyPost or had a webhook secret mismatch.
// TODO: This type will be renamed to MismatchWebhookSignatureError in a future release to match the other error types once the MismatchWebhookSignatureError helper is removed.
type MismatchWebhookSignatureErrorType struct {
LocalError // subtype of LocalError
}
// Unwrap returns the underlying LocalError error.
func (e *MismatchWebhookSignatureErrorType) Unwrap() error {
return &e.LocalError
}
// newMismatchWebhookSignatureError returns a new MismatchWebhookSignatureErrorType object.
func newMismatchWebhookSignatureError() *MismatchWebhookSignatureErrorType {
return &MismatchWebhookSignatureErrorType{LocalError{LibraryError{Message: MismatchWebhookSignature}}}
}
// MismatchWebhookSignatureError is raised when a webhook received did not originate from EasyPost or had a webhook secret mismatch.
// Deprecated: This helper will be removed in a future release. For access to the underlying message, use easypost.MismatchWebhookSignature instead.
var MismatchWebhookSignatureError = newMismatchWebhookSignatureError()
// ExternalApiError represents an error caused by an external API, such as a 3rd party HTTP API (not EasyPost).
type ExternalApiError struct {
LibraryError // subtype of LibraryError
}
// Unwrap returns the underlying LibraryError object.
func (e *ExternalApiError) Unwrap() error {
return &e.LibraryError
}
// newExternalApiError returns a new ExternalApiError object with the given message.
func newExternalApiError(message string) *ExternalApiError {
return &ExternalApiError{LibraryError{Message: message}}
}
// InvalidFunctionError is raised when a function call is invalid or not allowed.
type InvalidFunctionError struct {
LocalError // subtype of LocalError
}
// Unwrap returns the underlying LocalError error.
func (e *InvalidFunctionError) Unwrap() error {
return &e.LocalError
}
// newInvalidFunctionError returns a new InvalidFunctionError object with the given message.
func newInvalidFunctionError(message string) *InvalidFunctionError {
return &InvalidFunctionError{LocalError{LibraryError{Message: message}}}
}
// API/HTTP error types
// APIError represents an error that occurred while communicating with the EasyPost API.
//
// This is typically due to a specific HTTP status code, such as 4xx or 5xx.
//
// This is different from the Error class, which represents information about what triggered the failed request.
//
// The information from the top-level Error class is used to generate this error, and any sub-errors are stored in the Errors field.
type APIError struct {
LibraryError // subtype of LibraryError
// Code is a machine-readable status of the problem encountered.
Code string
// StatusCode is the HTTP numerical status code of the response.
StatusCode int
// Errors may be provided if there are details about server-side issues that caused the API request to fail.
Errors []*Error `json:"errors,omitempty" url:"errors,omitempty"`
}
// Error provides a pretty printed string of an APIError object based on present data.
func (e *APIError) Error() string {
if e.Message != "" {
if e.Code != "" {
return e.Code + " " + e.Message
}
return e.Message
}
if e.Code != "" {
return e.Code
}
return fmt.Sprintf("%d %s", e.StatusCode, e.Code)
}
func (e *APIError) Unwrap() error {
return &e.LibraryError
}
// BadRequestError is raised when the API returns a 400 status code.
type BadRequestError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *BadRequestError) Unwrap() error {
return &e.APIError
}
// ConnectionError is raised when the API returns a 0 status code.
type ConnectionError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *ConnectionError) Unwrap() error {
return &e.APIError
}
// GatewayTimeoutError is raised when the API returns a 504 status code.
type GatewayTimeoutError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *GatewayTimeoutError) Unwrap() error {
return &e.APIError
}
// InternalServerError is raised when the API returns a 500 status code.
type InternalServerError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *InternalServerError) Unwrap() error {
return &e.APIError
}
// InvalidRequestError is raised when the API returns a 422 status code.
type InvalidRequestError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *InvalidRequestError) Unwrap() error {
return &e.APIError
}
// MethodNotAllowedError is raised when the API returns a 405 status code.
type MethodNotAllowedError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *MethodNotAllowedError) Unwrap() error {
return &e.APIError
}
// NotFoundError is raised when the API returns a 404 status code.
type NotFoundError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *NotFoundError) Unwrap() error {
return &e.APIError
}
// PaymentError is raised when the API returns a 402 status code.
type PaymentError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *PaymentError) Unwrap() error {
return &e.APIError
}
// ProxyError is raised when the API returns a 407 status code.
type ProxyError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *ProxyError) Unwrap() error {
return &e.APIError
}
// RateLimitError is raised when the API returns a 429 status code.
type RateLimitError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *RateLimitError) Unwrap() error {
return &e.APIError
}
// RedirectError is raised when the API returns a 3xx status code.
type RedirectError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *RedirectError) Unwrap() error {
return &e.APIError
}
// RetryError is raised when the API returns a 1xx status code.
type RetryError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *RetryError) Unwrap() error {
return &e.APIError
}
// ServiceUnavailableError is raised when the API returns a 503 status code.
type ServiceUnavailableError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *ServiceUnavailableError) Unwrap() error {
return &e.APIError
}
// SSLError is raised when there is an issue with the SSL certificate.
type SSLError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *SSLError) Unwrap() error {
return &e.APIError
}
// TimeoutError is raised when the API returns a 408 status code.
type TimeoutError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *TimeoutError) Unwrap() error {
return &e.APIError
}
// UnauthorizedError is raised when the API returns a 401 status code.
type UnauthorizedError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *UnauthorizedError) Unwrap() error {
return &e.APIError
}
// ForbiddenError is raised when the API returns a 403 status code.
type ForbiddenError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *ForbiddenError) Unwrap() error {
return &e.APIError
}
// UnknownHttpError is raised when the API returns an unrecognized status code.
type UnknownHttpError struct {
APIError // subtype of APIError
}
// Unwrap returns the underlying APIError error.
func (e *UnknownHttpError) Unwrap() error {
return &e.APIError
}
// BuildErrorFromResponse returns an APIError-based object based on the HTTP response.
// Do not pass a non-error response to this function.
func BuildErrorFromResponse(response *http.Response) error {
// build the base APIError object from the response
apiError := &APIError{
StatusCode: response.StatusCode,
}
// deserialize the response body into a temporary object
buf, _ := ioutil.ReadAll(response.Body)
tmpError := &struct {
Error *Error `json:"error,omitempty" url:"error,omitempty"`
}{}
if json.Unmarshal(buf, &tmpError) == nil {
// extract the details from the temporary object (top-level Error class) and store them in the APIError object
apiError.Message = tmpError.Error.Message.(string)
apiError.Code = tmpError.Error.Code
apiError.Errors = tmpError.Error.Errors
} else {
// could not extract error details from the API response (or API did not return data, i.e. 1xx, 3xx or 5xx)
if response.Status == "" {
response.Status = ApiDidNotReturnErrorDetails
}
apiError.Message = response.Status
apiError.Code = ApiErrorDetailsParsingError
apiError.Errors = []*Error{}
}
// return the appropriate error type based on the status code
switch response.StatusCode {
case 0:
return &ConnectionError{APIError: *apiError}
case 100, 101, 102, 103:
return &RetryError{APIError: *apiError}
case 300, 301, 302, 303, 304, 305, 306, 307, 308:
return &RedirectError{APIError: *apiError}
case 400:
return &BadRequestError{APIError: *apiError}
case 401:
return &UnauthorizedError{APIError: *apiError}
case 402:
return &PaymentError{APIError: *apiError}
case 403:
return &ForbiddenError{APIError: *apiError}
case 404:
return &NotFoundError{APIError: *apiError}
case 405:
return &MethodNotAllowedError{APIError: *apiError}
case 407:
return &ProxyError{APIError: *apiError}
case 408:
return &TimeoutError{APIError: *apiError}
case 422:
return &InvalidRequestError{APIError: *apiError}
case 429:
return &RateLimitError{APIError: *apiError}
case 500:
return &InternalServerError{APIError: *apiError}
case 503:
return &ServiceUnavailableError{APIError: *apiError}
case 502, 504:
return &GatewayTimeoutError{APIError: *apiError}
default:
return &UnknownHttpError{APIError: *apiError}
}
}