-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_errors.go
94 lines (80 loc) · 2.34 KB
/
api_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
package apierrors
import (
"bytes"
_ "embed"
"encoding/json"
"fmt"
"strconv"
)
type ErrorDefinition struct {
LongMessage string `json:"long_message"`
ShortMessage string `json:"short_message"`
}
type Payload struct {
Code string `json:"code"`
LongMessage string `json:"long_message"`
ShortMessage string `json:"short_message"`
}
type ApiError struct {
StatusCode int
Payload Payload
}
// Reponse header field that holds the API Error Code
const ErrorCodeHeader = "X-Error-Code"
// Fallback ApiError that is returned if no matching ApiError is found
var Fallback = "50000"
// Expands a 5-digit errorCode to an ApiError. Returns ok = false if errorCode
// is undefined or invalid.
func FromCode(errorCode string) (ApiError, bool) {
apiError, ok := apiErrors[errorCode]
return apiError, ok
}
// Expands a 5-digit errorCode to an ApiError. Returns Fallback if code cannot
// be found.
func FromCodeOrFallback(errorCode string) ApiError {
apiError, ok := FromCode(errorCode)
if ok {
return apiError
}
apiError, ok = apiErrors[Fallback]
if !ok {
panic("fallback error code does not exist: " + errorCode)
}
return apiError
}
// Expands an HTTP status code to an ApiError. Returns Fallback if status
// cannot be expanded.
func FromStatusOrFallback(status int) ApiError {
return FromCodeOrFallback(fmt.Sprintf("%d00", status))
}
// Check if a string is an error code
func IsCode(maybeCode string) bool {
_, ok := FromCode(maybeCode)
return ok
}
var apiErrors = make(map[string]ApiError)
// the line below (go:embed...) is a directive, not a comment!
//
//go:embed api-errors.json
var jsonErrorDefinitions []byte
// init is a special function that is guaranteed to be called during the
// initialization of the package and before any other functions are called:
// https://go.dev/doc/effective_go#init
func init() {
var errorDefinitions map[string]ErrorDefinition
buf := bytes.NewBuffer(jsonErrorDefinitions)
if err := json.NewDecoder(buf).Decode(&errorDefinitions); err != nil {
panic("failed to decode ErrorDefinitions: " + err.Error())
}
for code := range errorDefinitions {
statusCode, _ := strconv.Atoi(code[0:3])
apiErrors[code] = ApiError{
StatusCode: statusCode,
Payload: Payload{
Code: code,
ShortMessage: errorDefinitions[code].ShortMessage,
LongMessage: errorDefinitions[code].LongMessage,
},
}
}
}