generated from milosgajdos/go-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
error.go
103 lines (88 loc) · 2.08 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
package playht
import (
"encoding/json"
"errors"
"fmt"
"strings"
)
var (
// ErrUnknown is returned when an unknown error occurrs.
ErrUnknown = errors.New("unknown error")
)
// APIError is a pseudo-sum type API error type.
type APIError struct {
Generic *ErrGeneric
Internal *ErrInternal
RateLimit *ErrRateLimit
UnexpecedError json.RawMessage
}
func (e *APIError) Error() string {
if e.Generic != nil {
return e.Generic.Error()
}
if e.Internal != nil {
return e.Internal.Error()
}
if e.RateLimit != nil {
return e.RateLimit.Error()
}
if len(e.UnexpecedError) > 0 {
return string(e.UnexpecedError)
}
return ErrUnknown.Error()
}
func (e *APIError) UnmarshalJSON(data []byte) error {
if strings.Contains(string(data), "Rate limit exceeded") {
e.RateLimit = &ErrRateLimit{Message: string(data)}
return nil
}
var genError ErrGeneric
err := json.Unmarshal(data, &genError)
if err == nil && genError.Message != "" {
e.Generic = &genError
return nil
}
var internalErr ErrInternal
err = json.Unmarshal(data, &internalErr)
if err == nil && len(internalErr.Message) > 0 {
e.Internal = &internalErr
return nil
}
e.UnexpecedError = data
return fmt.Errorf("failed decoding API error: %s", string(data))
}
// ErrGeneric is a generic API error.
type ErrGeneric struct {
ID string `json:"error_id"`
Message string `json:"error_message"`
}
// Error implements error interface.
func (e ErrGeneric) Error() string {
b, err := json.Marshal(e)
if err != nil {
return "unknown error"
}
return string(b)
}
// ErrInternal is an error returned
// when the API responds with 50x status code.
type ErrInternal struct {
Message string `json:"message"`
Err string `json:"error"`
}
// Error implements error interface.
func (e ErrInternal) Error() string {
b, err := json.Marshal(e)
if err != nil {
return "unknown error"
}
return string(b)
}
// ErrRateLimit is an error returned when the API rate limit is exceeded
type ErrRateLimit struct {
Message string
}
// Error implements error interface.
func (e ErrRateLimit) Error() string {
return e.Message
}