-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
72 lines (62 loc) · 1.94 KB
/
errors.go
File metadata and controls
72 lines (62 loc) · 1.94 KB
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
package netloc8
import (
"fmt"
)
// APIError represents a structured error response from the NetLoc8 API.
// It implements the error interface and supports errors.As for typed
// error handling.
type APIError struct {
// Status is the HTTP status code (e.g. 400, 403, 404, 429, 500).
Status int `json:"-"`
// Code is the machine-readable error code (e.g. "INVALID_IP",
// "FORBIDDEN", "RATE_LIMIT_EXCEEDED").
Code string `json:"code"`
// Message is the human-readable error description.
Message string `json:"message"`
// RequestID is the unique request identifier, if returned.
RequestID string `json:"requestId,omitempty"`
}
// Error implements the error interface.
func ( e *APIError ) Error() string {
if e.Code != "" {
return fmt.Sprintf( "netloc8: %s — %s (HTTP %d)", e.Code, e.Message, e.Status )
}
return fmt.Sprintf( "netloc8: HTTP %d", e.Status )
}
// apiErrorResponse is the raw JSON envelope returned by the API on error.
type apiErrorResponse struct {
Query *struct {
Type string `json:"type"`
Value string `json:"value"`
} `json:"query,omitempty"`
Error *struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
Meta *struct {
RequestID string `json:"requestId"`
} `json:"meta,omitempty"`
}
// IsNotFound reports whether the error is a 404 Not Found response.
func IsNotFound( err error ) bool {
if apiErr, ok := err.( *APIError ); ok {
return apiErr.Status == 404
}
return false
}
// IsRateLimited reports whether the error is a 429 Rate Limit Exceeded response.
func IsRateLimited( err error ) bool {
if apiErr, ok := err.( *APIError ); ok {
return apiErr.Status == 429
}
return false
}
// IsForbidden reports whether the error is a 403 Forbidden response.
// This typically means the API key lacks the required scope or the
// origin does not match.
func IsForbidden( err error ) bool {
if apiErr, ok := err.( *APIError ); ok {
return apiErr.Status == 403
}
return false
}